//
//  ReadView.m
//  KidReading
//
//  Created by telen on 14/12/24.
//  Copyright (c) 2014年 刘赞黄Telen. All rights reserved.
//

#import "ReadView.h"
#import "ConstDefine.h"
#import "ReadPageDot.h"

#define __PageWebViewTag_loading 101010 //loading
#define __PageWebViewTag_quiz 191919 //Quiz
#define __PageWebViewTag_contentH5 80808 //h5内容嵌入

#define __Debug_KoK_rect 0 //是否开启 卡拉OK的格子

#pragma mark- GoToPage
@implementation GoToPage
@end

@implementation KoK_ClipView
- (void)dealloc
{
#if __Debug_is_dealloced_log_2
    NSLog(@"dealloc: %@",NSStringFromClass([self class]));
#endif
}
@end

@interface KoK_RectView ()
@property(nonatomic,assign)BOOL isScaleView;
@end

@implementation KoK_RectView
-(void)addBorders{
    self.layer.borderColor = [UIColor greenColor].CGColor;
    self.layer.borderWidth = 1.0;
}
- (void)dealloc
{
    self.keyWordPinyin = nil;
    self.keyWord = nil;
    self.word = nil;
#if __Debug_is_dealloced_log_2
    NSLog(@"dealloc: %@",NSStringFromClass([self class]));
#endif
}
@end
//
@interface TLEventView_Page : TLEventView
@end
@implementation TLEventView_Page
//-(UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event{
//    UIView* view = nil;
//    for (KoK_RectView* subView in self.subviews) {
//        if ([subView isKindOfClass:[KoK_RectView class]]) {
//            if (CGRectContainsPoint(subView.frame, point)) {
//                if (subView.keyWord != nil) {
//                    view = subView;
//                }
//            }
//        }
//    }
//    NSSet* touches = [event allTouches];
//    UITouch* touch = [touches anyObject];
//    if (touch.tapCount == 1) {
//        NSLog(@"单击");
//    }else if (touch.tapCount == 2){
//        NSLog(@"双击");
//    }
//    if (view) {
//        return view;
//    }
//    return [super hitTest:point withEvent:event];
//}

@end

//UITapGestureRecognizer子类
@interface UITapGestureRecognizer_SEL : UITapGestureRecognizer
@property(nonatomic,copy)NSString* selStr;
@property(nonatomic,weak)id target_sel;
@end

@implementation UITapGestureRecognizer_SEL
-(instancetype)initWithTarget:(id)target action:(SEL)action{
    if (self = [super initWithTarget:target action:action]){
        self.selStr = NSStringFromSelector(action);
        self.target_sel = target;
    }
    return self;
}

@end

#pragma mark- PageView
@interface PageView ()<DataProcessingAsyncSoudConvertFilesDelegate,StatusButton_2_ViewDelegate>
@end

@implementation PageView
{
    NSMutableArray* SReadBtnMArr;
}

@synthesize cn_View = cn_View;
@synthesize en_View = en_View;
@synthesize py_View = py_View;
@synthesize zoomView = zoomView;
@synthesize bookType = btype;
@synthesize contentView_Scale = contentView;

- (void)dealloc
{
    self.kokColor = nil;
    self.nameFolder = nil;
    [[DataProcessing shareSingle] unRegSoundDelegate:self];
#if __Debug_is_dealloced_log
    NSLog(@"dealloc: %@",NSStringFromClass([self class]));
#endif
}

- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        boundCenter = CGPointMake(frame.size.width/2, frame.size.height/2);
        kok_ClipViewArr = [[NSMutableArray alloc] initWithCapacity:0];
        kok_RectViewArr_sentence = [[NSMutableArray alloc] initWithCapacity:0];
        mp3Arr = [[NSMutableArray alloc] initWithCapacity:0];
        dict_prevGoToPage = [NSMutableDictionary new];
        dict_nextGoToPage = [NSMutableDictionary new];
        SReadBtnMArr = [[NSMutableArray alloc] initWithCapacity:0];
        //
        frame.origin = CGPointZero;
        zoomView = [[UIScrollView alloc] initWithFrame:frame];
        [self addSubview:zoomView];
        zoomView.delegate = self;
        zoomView.bounces = NO;
        zoomView.bouncesZoom = NO;
        if([DataProcessing shareSingle].deviceType == DevicesTypes_iPhone)
        {
            zoomView.bouncesZoom = YES;
        }
        zoomView.alwaysBounceHorizontal = YES;
        //
        contentView = [[UIView alloc] initWithFrame:frame];
        contentView.backgroundColor = [UIColor clearColor];
        [zoomView addSubview:contentView];
        // Add gesture,double tap zoom imageView.
        UITapGestureRecognizer_SEL *doubleTapGesture = [[UITapGestureRecognizer_SEL alloc] initWithTarget:self
                                                                                           action:@selector(handleDoubleTap:)];
        [doubleTapGesture setNumberOfTapsRequired:2];
        //[contentView addGestureRecognizer:doubleTapGesture];
        doubleTapGesture.rippleColor = __BaseBackColor;
        [doubleTapGesture addTapRipple];
        //
        [[DataProcessing shareSingle] regSoundDelegate:self];
    }
    return self;
}
//设置最大放大倍数
-(void)setMax_scale:(CGFloat)max_scale{
    _max_scale = max_scale;
    if (max_scale == 0) {
        _max_scale = __PageScaleMax_;
    }
}

- (void)addWaittingView
{
    _isWaiting = YES;
#if __ShowWaiting_Sub
    UIActivityIndicatorView* loading = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    loading.center = CGPointMake(self.frame.size.width/2, self.frame.size.height/2);
    [loading startAnimating];
    [contentView addSubview:loading];
    //
    loading.translatesAutoresizingMaskIntoConstraints = NO;
    [loading lyt_centerInParent];
#else
    [self addLoadingAnimationToView:contentView];
#endif
}

- (StatusButton_2_View*)newPlayStatusBtn_scale:(CGFloat)scale
{
    CGFloat ratio = [DataProcessing shareSingle].ratio_w;
    CGRect frame = CGRectMake(0, 0, 40.0*scale/ratio, 40.0*scale/ratio);
    StatusButton_2_View* soundBtn = [[StatusButton_2_View alloc] initWithFrame:frame imageOn:@"" imageOff:@"page_icon_speaker_stop.png"];
    NSArray* arrAni = [NSArray arrayWithObjects:[UIImage imageNamed:@"page_icon_speaker_play1.png"],[UIImage imageNamed:@"page_icon_speaker_play2.png"], nil];
    [soundBtn setAni_UImageArr:arrAni ani_duration:1 forStatus:YES];
    [soundBtn setButtonStatus:NO];
    soundBtn.delegate = self;
    return soundBtn;
}

- (StatusButton_2_View*)newPlayStatusBtn_frame:(CGRect)frame
{
    StatusButton_2_View* soundBtn = [[StatusButton_2_View alloc] initWithFrame:frame imageOn:@"" imageOff:@"page_icon_speaker_stop.png"];
    NSArray* arrAni = [NSArray arrayWithObjects:[UIImage imageNamed:@"page_icon_speaker_play1.png"],[UIImage imageNamed:@"page_icon_speaker_play2.png"], nil];
    [soundBtn setAni_UImageArr:arrAni ani_duration:1 forStatus:YES];
    [soundBtn setButtonStatus:NO];
    soundBtn.delegate = self;
    return soundBtn;
}

- (StatusButton_2_View*)newPepPlayStatusBtn_frame:(CGRect)frame
{
    StatusButton_2_View* soundBtn = [[StatusButton_2_View alloc] initWithFrame:frame imageOn:@"" imageOff:@"page_btn_suona1.png"];
    NSArray* arrAni = [NSArray arrayWithObjects:[UIImage imageNamed:@"page_btn_suona2.png"],[UIImage imageNamed:@"page_btn_suona3.png"], nil];
    [soundBtn setAni_UImageArr:arrAni ani_duration:1 forStatus:YES];
    [soundBtn setButtonStatus:NO];
    soundBtn.delegate = self;
    return soundBtn;
}

- (void)statusButton_2_View_didClicked:(StatusButton_2_View *)sbview
{
    if(sbview.onOff)for (StatusButton_2_View* sbtn in SReadBtnMArr) {
        if (sbtn != sbview && sbtn.onOff == YES) {
            [sbtn setButtonStatus:NO];
            //[((ReadView*)self.tapCallBackDelegate) performSelector:@selector(sreadBtn_ChangeStatus:) withObject:sbtn];
            [NSObject msgToTarget:self.tapCallBackDelegate menthed:@"sreadBtn_ChangeStatus:" refs:@[sbtn] needReturnValue:NO];
        }
    }
    //[((ReadView*)self.tapCallBackDelegate) performSelector:@selector(sreadBtn_ChangeStatus:) withObject:sbview];
    [NSObject msgToTarget:self.tapCallBackDelegate menthed:@"sreadBtn_ChangeStatus:" refs:@[sbview] needReturnValue:NO];
}

#pragma mark-

- (NSString*)logPageJson
{
    return [NSString stringWithFormat:@"bookid:(%@-%@) pageindex:%@ pagejson: %@",@(self.bookid),@(self.bookOid),@(self.pageIndex),pageDict];
}

//MARK: UpdatePageShowing
- (void)updatePageShowing_must
{
    NSString* name = [self.nameFolder stringByAppendingPathComponent:@"page.json"];
    NSString* pagejsonPath = [DataProcessing bookPathForBookID:self.bookid subDir:name];
    NSData* data = [NSData dataWithContentsOfFile:pagejsonPath];
    [self updatePageShowing:data];
}

- (void)updatePageShowing_AsyncCtr:(void(^)(BOOL hasData))will comp:(void(^)(BOOL hasData))comp
{
    [DataProcessing do_Async_high:^{
        NSString* name = [self.nameFolder stringByAppendingPathComponent:@"page.json"];
        NSString* pagejsonPath = [DataProcessing bookPathForBookID:self.bookid subDir:name];
        NSData* data = [NSData dataWithContentsOfFile:pagejsonPath];
        BOOL hasData = data ? YES : NO;
        if(hasData && _isWaiting){
            [DataProcessing do_Main_quick:^{
                [self updatePageShowing:data];
                comp(hasData);
            }];
        }
    } delay:0];
}
- (void)updatePageShowing
{
    [DataProcessing do_Async_high:^{
        NSString* name = [self.nameFolder stringByAppendingPathComponent:@"page.json"];
        NSString* pagejsonPath = [DataProcessing bookPathForBookID:self.bookid subDir:name];
        NSData* data = [NSData dataWithContentsOfFile:pagejsonPath];
        [DataProcessing do_Main_quick:^{
            [self updatePageShowing:data];
        }];
    } delay:0];
}
- (void)updatePageShowing:(NSData*)data
{
    _memoView = nil, _scrapView = nil,_scrawlView = nil,_hotView = nil;
    cn_View = en_View = py_View = kok_View = nil;
    _readFunctionPage = nil;
    _hasEnglishWords = _hasChineseWords = _hasPinyinWords = _hasSounds = _hasSounds_fast = _hasSounds_slower = _hasTrans = NO;
    _paragraph_suffix = _article_suffix = NO;
    _isDataDisplay = NO;
    _isWaiting = NO;
    _paragraph_prev_suffix_index = _article_prev_suffix_index = nil;
    [kok_ClipViewArr removeAllObjects];
    [kok_RectViewArr_sentence removeAllObjects];
    [SReadBtnMArr removeAllObjects];
    if (mp3Arr) {
        for (NSString* key in mp3Arr) {
            if(key.length==0)continue;
            NSString* mp3F = key;
            mp3F = [DataProcessing bookPathForBookID:self.bookid subDir:mp3F];
            if(((ReadView*)self.tapCallBackDelegate).goToPage_Action == NO)[[TLSoundPlayer shareSingle] stopFilePlay_andClean:mp3F];//跨页播放下，不清理MP3
        }
    }
    [mp3Arr removeAllObjects];
    [dict_nextGoToPage removeAllObjects];
    [dict_prevGoToPage removeAllObjects];
    [contentView removeAllSubViews];
    //
    float minimumScale = self.frame.size.width / contentView.frame.size.width;
    [zoomView setMinimumZoomScale:minimumScale];
    [zoomView setMaximumZoomScale:_max_scale];
    [zoomView setZoomScale:minimumScale];
    //
    //附件功能通用标签
    NSInteger webViewTag = __PageWebViewTag_quiz;//FuctionView
    UIView* v = [self viewWithTag:webViewTag];
    if (v) {
        [v removeFromSuperview];
    }
    //
    if (self.nameFolder == nil && self.zipPartIndex == -1) {
        return;
    }
    
    //UI显示
    void(^showPageUI)(void) = ^{
        if (!data) {
            if (self.pageType == BookPageType_pQuiz) {
                CGRect frame = self.bounds;
                frame.origin.y = 60/([DataProcessing shareSingle].ratio_w);
                frame.size.height -= frame.origin.y;
                UIWebView* webview = [[UIWebView alloc] initWithFrame:frame];
                webview.mediaPlaybackRequiresUserAction = NO;
                webview.allowsInlineMediaPlayback = YES;
                webview.scrollView.scrollEnabled = NO;
                webview.tag = webViewTag;
                //webview.scalesPageToFit = YES;
                webview.paginationMode = UIWebPaginationModeTopToBottom;//从上而下
                webview.scrollView.pagingEnabled = YES;
                webview.backgroundColor = [UIColor clearColor];
                NSString* fullURL = [DataProcessing fullQuizUrl:self.nameFolder];
                
                [[RNCachingURLProtoclSetting getInstance] addURLForCaching:fullURL edition:self.quizEdition];
                
                [webview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:fullURL]]];
                [self addSubview:webview];
                //
                webview.delegate = self;
                //
                [zoomView setMaximumZoomScale:minimumScale];
            }else if(self.pageType == BookPageType_pAccessibility) {
#ifdef JReaderSDKControl
#else
#ifndef WHY_PJ
                Class cReadFunctionPage = NSClassFromString(@"ReadFunctionPage");
                if (cReadFunctionPage) {
                    NSValue* frameValue = [NSValue valueWithCGRect:self.bounds];
                    UIView* view = [NSObject msgToClassName:@"ReadFunctionPage" menthed:@"readFuntionPageView_frame:" refs:@[frameValue] needReturnValue:YES];
                    view.tag = webViewTag;
                    [self addSubview:view];
                    UIButton* talkBtn = [view msgTo_menthed:@"talk_btn" refs:@[] needReturnValue:YES];
                    if (talkBtn) {
                        [talkBtn addTarget:self action:@selector(click_talk) forControlEvents:UIControlEventTouchUpInside];
                    }
                    _readFunctionPage = (ReadFunctionPage*)view;
                }
#endif
                
#endif
            }else{
                [self addWaittingView];
            }
            return;
        }
        if (data) {
            pageDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
#if __Debug_BooksFileReading
            NSLog(@"bookid:%d pageindex:%d pagejson: %@",self.bookid,self.pageIndex,pageDict);
#endif
            //        NSLog(@"%@",pageDict);
            //中文还是英文书
            NSNumber* btp = [pageDict objectForKey:@"btype"];
            nullToNil(btp);
            btype = (int)[btp integerValue];//0中文，1英文
            
            //PageId
            self.pageId = pageDict[@"page_id"];
            if (self.pageId == nil || self.pageId.length <= 0) {
                self.pageId = @(self.pageIndex).description;
            }
            
            //背景
            NSDictionary* img = [pageDict objectForKey:@"img"];
            nullToNil(img);
            NSArray* bg = [img objectForKey:@"bg"];
            nullToNil(bg);
            [self addBgImageWithArr:bg withSuperView:nil];
            
            //封面 封底
            if (self.pageType == BookPageType_pForeCover
                || self.pageType == BookPageType_pBackCover) {
                NSString* title_mp3 = [pageDict objectForKey:@"title_mp3"];
                nullToNil(title_mp3);
                if (title_mp3 && title_mp3.length > 0) {
                    [mp3Arr removeAllObjects];
                    [dict_prevGoToPage removeAllObjects];
                    [dict_nextGoToPage removeAllObjects];
                    [mp3Arr addObject:title_mp3];
                }
            }
            //目录
            if (self.pageType == BookPageType_pMenu) {
                
            }
            //内容
            [self addPageContent];
            
            //prepare MP3
            if (mp3Arr && mp3Arr.count >0) {
                _hasSounds = YES;
                for (NSString* key in mp3Arr) {
                    if(key.length==0)continue;
                    NSString* mp3F = key;
                    mp3F = [DataProcessing bookPathForBookID:self.bookid subDir:mp3F];
                    //[[TLSoundPlayer shareSingle] prepareToPlayFile:mp3F fromTime:0];
                    //
                    [self soudFilesConvert:mp3F];
                }
            }
            //
            _isDataDisplay = YES;
            //
            //代理返回 加载完成，通知delegate
            [NSObject msgToTarget:self.tapCallBackDelegate menthed:@"readViewDidLoadSuccess_PageView:" refs:@[self] needReturnValue:NO];
        }
    };
    
    if ([NSThread isMainThread]) {
        showPageUI();
    }else{
        [DataProcessing do_Main_quick:^{
            showPageUI();
        }];
    }
}

- (void)DataProcessing_soudFilesAsyncConvertSuccess:(NSString *)ose toFiles:(NSString *)outFile
{
    NSArray *tempArr = [mp3Arr copy];
    if (tempArr && tempArr.count >0) {
        _hasSounds = YES;
        _hasSounds_fast = YES;
        _hasSounds_slower = YES;
        for (NSString* key in tempArr) {
            if(key.length==0)continue;
            NSString* ose = [DataProcessing bookPathForBookID:self.bookid subDir:key];
            NSString* fastFile = [DataProcessing getFastSoudFilePathFromPath:ose];
            NSString* slowerFile = [DataProcessing getSlowerSoudFilePathFromPath:ose];
            if (![[NSFileManager defaultManager] fileExistsAtPath:fastFile]) {
                _hasSounds_fast = NO;
            }
            if (![[NSFileManager defaultManager] fileExistsAtPath:slowerFile]) {
                _hasSounds_slower = NO;
            }
        }
    }
    tempArr = nil;
}

- (void)soudFilesConvert:(NSString*)ose
{
#ifndef WHY_PJ
    NSString* fastFile = [DataProcessing getFastSoudFilePathFromPath:ose];
    NSString* slowerFile = [DataProcessing getSlowerSoudFilePathFromPath:ose];
    [self DataProcessing_soudFilesAsyncConvertSuccess:ose toFiles:fastFile];
    if (_hasSounds_fast && _hasSounds_slower) {
        return;
    }

    [DataProcessing do_Async_low:^{
        [[DataProcessing shareSingle] soundFilesAsyncConvert:ose toFiles:fastFile speedRatio:[DataProcessing shareSingle].soundPlayRatio_fast];
        [[DataProcessing shareSingle] soundFilesAsyncConvert:ose toFiles:slowerFile speedRatio:[DataProcessing shareSingle].soundPlayRatio_slower];
    } delay:0];
#endif
}

- (KoK_ClipView*)kok_ClipViewForRectView:(KoK_RectView*)rectview
{
    for (KoK_ClipView* clipview in kok_ClipViewArr) {
        if (CGRectContainsPoint(clipview.frameFull, rectview.center)
            || CGRectContainsPoint(clipview.frameFull, rectview.center_25y)
            || CGRectContainsPoint(clipview.frameFull, rectview.center_75y)
            || CGRectContainsPoint(clipview.frameFull, rectview.center_25x)
            || CGRectContainsPoint(clipview.frameFull, rectview.center_75x)) {
            return clipview;
        }
    }
    return nil;
}

- (void)update_KOK_toPlayMSecond:(NSTimeInterval)msec andSentenceIndex:(NSInteger)index
{
    //index 数据
    NSArray* sarr = nil;
    CGRect frame;
    //条件判断清理，仅针对 0，0
    if(msec == index && index == 0)for (int i =0; i<kok_RectViewArr_sentence.count; i++) {
        sarr = [kok_RectViewArr_sentence objectAtIndex:i];
        if (i< index) {
            for (KoK_RectView* rectview in sarr) {
                if (!rectview.word) {
                    continue;
                }
                KoK_ClipView* clipview = [self kok_ClipViewForRectView:rectview];
                if (clipview) {
                     clipview.frame = clipview.frameFull;
                }
            }
        }else{
            for (KoK_RectView* rectview in sarr) {
                if (!rectview.word) {
                    continue;
                }
                KoK_ClipView* clipview = [self kok_ClipViewForRectView:rectview];
                if (clipview) {
                    frame = clipview.frameFull;
                    frame.size.width = 0;
                    clipview.frame = frame;
                }
            }
        }
    }
    
    //句段篇跳转
    void(^gotoNext)(KoK_RectView* rectview,CGFloat ratio) = ^(KoK_RectView* rectview,CGFloat ratio){
        if (rectview.goPage && rectview.goPage.type == GoToPageType_next && ratio > 0.4) {
            ReadView* readview = (ReadView*)self.tapCallBackDelegate;
            if(readview && readview.goToPage_Action == NO){
                readview.goToPage_Action = YES;
                readview.goPage = rectview.goPage;
                [DataProcessing do_Main:^{
                    if (rectview.goPage.offset == 1) {
                        [self update_KOK_toPlayMSecond:0 andSentenceIndex:0];
                        [readview nextPage_quick];
                    }else{
                        [readview updateShowPageToIndex:self.pageIndex+rectview.goPage.offset];
                        [DataProcessing do_Main:^{
                            if (readview.delegate && [readview.delegate respondsToSelector:@selector(readViewDidScrolledTo:)]) {
                                [readview.delegate readViewDidScrolledTo:readview.currentPageView];
                            }
                        } delay:0.1];
                    }
                } delay:0.3];
            }
        }
    };
    
    //msec
    if(kok_RectViewArr_sentence.count >index)
    {
        sarr = [kok_RectViewArr_sentence objectAtIndex:index];
        for (KoK_RectView* rectview in sarr) {
            if (!rectview.word) {
                continue;
            }
            KoK_ClipView* clipview = [self kok_ClipViewForRectView:rectview];
            if (clipview) {
                if(rectview.endMS <= msec){
                    frame = clipview.frameFull;
                    frame.size.width = (rectview.frame.origin.x+rectview.frame.size.width)-frame.origin.x;
                    clipview.frame = frame;
                }else if(rectview.biganMS < msec && rectview.endMS > msec){
                    CGFloat ratio = (msec-rectview.biganMS)*1.0/(rectview.endMS-rectview.biganMS);
                    frame = clipview.frameFull;
                    CGFloat www = (rectview.frame.origin.x+rectview.frame.size.width*ratio)-frame.origin.x;
                    frame.size.width = www >=0 ? www : 0;
                    clipview.frame = frame;
                    gotoNext(rectview,ratio);
                    break;
                }
            }else{
                if(rectview.biganMS < msec && rectview.endMS > msec){
                    CGFloat ratio = (msec-rectview.biganMS)*1.0/(rectview.endMS-rectview.biganMS);
                    gotoNext(rectview,ratio);
                }
            }
        }
    }
    
}

- (NSArray *)getMp3Arr
{
    return mp3Arr;
}

- (GoToPage *)prevGo:(NSInteger)mp3Index
{
    return dict_prevGoToPage[@(mp3Index).description];
}

- (GoToPage *)nextGo:(NSInteger)mp3Index
{
    return dict_nextGoToPage[@(mp3Index).description];
}

- (NSString*)getTrans
{
    return trans;
}

- (void)enumerateSreadBtnUsingBlock:(void (^)(StatusButtonView * _Nonnull, NSUInteger, BOOL * _Nonnull))blk
{
    [SReadBtnMArr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        blk(obj,idx,stop);
    }];
}

- (void)hideSreadBtns:(BOOL)yn
{
    for (StatusButton_2_View* sbtn in SReadBtnMArr) {
        sbtn.hidden = yn;
    }
}

- (void)stopSreadBtns {
    for (StatusButton_2_View* sbtn in SReadBtnMArr) {
        [sbtn setButtonStatus:NO];
    }
}

- (void)do_normalLayer_scrawl_scrap_memo
{
    if (_memoView && _scrapView && _scrawlView) {
        [contentView insertSubview:_scrawlView belowSubview:_memoView];
        [contentView insertSubview:_scrapView belowSubview:_memoView];
        _memoView.eventType = TLViewEvent_JustForSubViews;
        _scrapView.eventType = _scrawlView.eventType = TLViewEvent_never;
        _scrapView.editModel = _scrawlView.editModel = _memoView.editModel = NO;
        ((ReadView*)self.tapCallBackDelegate).pageScroll.scrollEnabled = YES;
        self.zoomView.maximumZoomScale = _max_scale;
    }
}

- (void)do_foucusLayer_scrawl_scrap_memo:(TLEventView *)foucusEventView
{
    [DataProcessing do_Main_quick:^{        
        [self do_normalLayer_scrawl_scrap_memo];
        if (foucusEventView != _memoView) {
            [contentView  insertSubview:foucusEventView aboveSubview:_memoView];
        }
        foucusEventView.eventType = TLViewEvent_all;
        foucusEventView.editModel = YES;
        CGFloat zscale = self.zoomView.minimumZoomScale;
        [self.zoomView setZoomScale:zscale animated:YES];
        self.zoomView.maximumZoomScale = zscale;
//        ((ReadView*)self.tapCallBackDelegate).pageScroll.scrollEnabled = NO;
        [DataProcessing do_Async:^{
            ((ReadView*)self.tapCallBackDelegate).pageScroll.scrollEnabled = NO;
        } delay:0.3f];
    }];
}

- (void)addPageContentView
{
    //Layer
    if (self.pageType == BookPageType_pContent) {
        cn_View = [[UIView alloc] initWithFrame:self.bounds];
        en_View = [[UIView alloc] initWithFrame:self.bounds];
        py_View = [[UIView alloc] initWithFrame:self.bounds];
        kok_View = [[UIView alloc] initWithFrame:self.bounds];
        [contentView addSubview:cn_View];
        [contentView addSubview:en_View];
        [contentView addSubview:py_View];
        [contentView addSubview:kok_View];
        cn_View.userInteractionEnabled = NO;
        en_View.userInteractionEnabled = NO;
        py_View.userInteractionEnabled = NO;
        kok_View.userInteractionEnabled = NO;
    }
    //
    _hotView = [[TLEventView_Page alloc] initWithFrame:self.bounds];
    [contentView addSubview:_hotView];
    _hotView.eventType = TLViewEvent_JustForSubViews;//Event
    //
    if (self.pageType == BookPageType_pContent) {
        _scrawlView = [[ReadPageView_Scrawl alloc] initWithFrame:self.bounds];
        _scrapView = [[ReadPageView_Scrap alloc] initWithFrame:self.bounds];
        _memoView = [[ReadPageView_Memo alloc] initWithFrame:self.bounds];
        [contentView addSubview:_scrawlView];
        [contentView addSubview:_scrapView];
        [contentView addSubview:_memoView];
        _scrawlView.bookRatioWH = self.bookRatioWH;
        //
        _scrawlView.rootView = self.tapCallBackDelegate;
        _scrapView.pageview = self;
        //Event
        [self do_normalLayer_scrawl_scrap_memo];
        //[_scrapView addPanGesture_Undo];
        //[_memoView addPanGesture_Undo];
        //[_scrawlView addPanGesture_Undo];
    }
    
}

- (void)addPageContent
{
    [self addPageContentView];
    if (self.pageType == BookPageType_pContent) {
        //单页kok取色
        NSString* clrstr = [pageDict objectForKey:@"kok_cl"];
        nullToNil(clrstr);
        UIColor* kokClr = [UIColor colorWithHexString:clrstr];
        if (kokClr) {
            self.kokColor = kokClr;
        }else if([@"###" isEqualToString:clrstr]){ //卡拉ok 不着色
            self.kokColor = [[UIColor blueColor] colorWithAlphaComponent:0];
        }
        //其他功能后添加
        NSDictionary* img = [pageDict objectForKey:@"img"];
        nullToNil(img);
        NSDictionary* fg = [img objectForKey:@"fg"];
        nullToNil(fg);
        NSArray* cnArr = [fg objectForKey:@"cn"];
        nullToNil(cnArr);
        [self addImageWithArr:cnArr withSuperView:cn_View];
        if(cnArr && cnArr.count >0)_hasChineseWords = YES;
        NSArray* enArr = [fg objectForKey:@"en"];
        nullToNil(enArr);
        if(enArr && enArr.count >0)_hasEnglishWords = YES;
        [self addImageWithArr:enArr withSuperView:en_View];
        NSArray* pyArr = [fg objectForKey:@"py"];
        nullToNil(pyArr);
        [self addImageWithArr:pyArr withSuperView:py_View];
        if(pyArr && pyArr.count >0)_hasPinyinWords = YES;
        //卡拉OK
        if (btype == 1) {
            [self add_KOK_ImageWithArrr:enArr];
        }else{
            [self add_KOK_ImageWithArrr:cnArr];
        }
        //字词定位
        [self addRectForWord];
        //准备跟读数据
        if ([ReadBookVOrH_VC currentReadInstance].evaluateDict.count > 0 && [[[ReadBookVOrH_VC currentReadInstance].evaluateDict valueForKey:@"data_src"] isEqualToString:@"json"]) {
            [self readyEvaluateData];
        }
        //播放按钮定位sread
        [self addSubReadBtns];
        //播放按钮定位sread_adv
        [self addSubRead_adv_Btns];
    }
    //热区 host_area
    [self addHostAreaBtns];
    //新热区
    [self addHostArea_adv_Btns];
}


- (NSString*)addHostArea_adv_Img_Sign:(UIScrollView*)scrollview
{
    NSString* rollType = nil;
    //处理图片滚动示意标签
    if (scrollview && scrollview.superview) {
        CGFloat sw = scrollview.frame.size.width;
        CGFloat sh = scrollview.frame.size.height;
        CGFloat iw = scrollview.contentSize.width;
        CGFloat ih = scrollview.contentSize.height;
        CGPoint ct = scrollview.superview.center;
        CGFloat pod = 16;
        CGRect frame = scrollview.frame;
        if (sw < iw  && sh < ih) {
            UIImage* image = [UIImage imageNamed:@"page_icon_picture3.png"];
            frame.size = CGSizeMake(image.size.width*0.5, image.size.height*0.5);
            frame.origin = CGPointMake(pod, pod);
            UIImageView* imgv = [[UIImageView alloc] initWithFrame:frame];
            imgv.image = image;
            [scrollview.superview addSubview:imgv];
            rollType = @"round";
        }else if(sh < ih){
            UIImage* image = [UIImage imageNamed:@"page_icon_picture1.png"];
            frame.origin.y += pod;
            if (ct.x <= contentView.center.x) {
                frame.origin.x += frame.size.width-pod-image.size.width*0.5;
            }else{
                frame.origin.x += pod;
            }
            frame.size = CGSizeMake(image.size.width*0.5, image.size.height*0.5);
            UIImageView* imgv = [[UIImageView alloc] initWithFrame:frame];
            imgv.image = image;
            [scrollview.superview addSubview:imgv];
            rollType = @"upDown";
        }else if(sw < iw){
            UIImage* image = [UIImage imageNamed:@"page_icon_picture2.png"];
            frame.origin.y += frame.size.height-pod;
            frame.origin.x += frame.size.width-pod;
            frame.size = CGSizeMake(image.size.width*0.5, image.size.height*0.5);
            frame.origin.y += -frame.size.height;
            frame.origin.x += -frame.size.width;
            UIImageView* imgv = [[UIImageView alloc] initWithFrame:frame];
            imgv.image = image;
            [scrollview.superview addSubview:imgv];
            rollType = @"leftRight";
            //
            if([scrollview isKindOfClass:[PageImageScrollView class]])[(PageImageScrollView*)scrollview addPanForScrollView];
        }
    }
    return rollType;
}

- (CGRect)getRect:(NSString*)str
{
    NSArray* rect = [DataProcessing getNumbersFromString:str];
    if (rect.count != 4) {
        rect = @[@(0),@(0),@(0),@(0)];
    }
    CGFloat w = [rect[2] floatValue] -[rect[0] floatValue];
    CGFloat h = [rect[3] floatValue] -[rect[1] floatValue];
    CGFloat x = [rect[0] floatValue];
    CGFloat y = [rect[1] floatValue];
    w *= self.bookRatioWH;
    h *= self.bookRatioWH;
    x *= self.bookRatioWH;
    y *= self.bookRatioWH;
    return CGRectMake(floor(x), floor(y), ceil(w), ceil(h));
}

- (void)addHostArea_adv_Btns
{
    NSDictionary* region = [pageDict objectForKey:@"region"];
    nullToNil(region);
    NSArray* hot_area = [region objectForKey:@"hot_area_adv"];
    nullToNil(hot_area);
    //
    NSMutableArray* alertRectViewArray = [NSMutableArray new];
    //
    if (hot_area && hot_area.count > 0) {
        for (NSDictionary* dict in hot_area) {
            NSDictionary* local = dict[@"local"];
            nullToNil(local);
            NSDictionary* helper = dict[@"helper"];
            nullToNil(helper);
            NSDictionary* popup = dict[@"popup"];
            nullToNil(popup);
            NSNumber* mutex = dict[@"mutex"];
            nullToNil(mutex);
            NSString *srcId = [dict valueForKey:@"src_id"];
            nullToNil(srcId);
            //
            
            CGRect rect = [self getRect:[dict objectForKey:@"rect"]];
            CGFloat w = rect.size.width;
            CGFloat h = rect.size.height;
            CGFloat x = rect.origin.x;
            CGFloat y = rect.origin.y;
            //
            KoK_RectView* rectview = [[KoK_RectView alloc] initWithFrame:CGRectMake(x, y, w, h)];
            rectview.isScaleView = YES;
            rectview.isHot_Area = YES;
            rectview.hot_adv_popup = popup;
            rectview.src_id = srcId;
            if(mutex)rectview.mutex = [mutex integerValue];
            
            BOOL needTapEvent = YES;
            BOOL needTapEvent_Scale = NO;
            if (local && local.count > 0) {
                NSString* ecodetype = local[@"encode_type"];
                nullToNil(ecodetype);
                BOOL needDecode = [ecodetype isEqualToString:@"normal"];
                NSString* hottype = local[@"type"];
                nullToNil(hottype);
                NSString* mode = local[@"mode"];
                nullToNil(mode);
                BOOL mode1_1 = [mode isEqualToString:@"1:1"];
                NSArray* source = local[@"source"];
                nullToNil(source);
                NSString* status = local[@"status"];
                nullToNil(status);
                BOOL status_valid = [status isEqualToString:@"valid"];
                NSString* gallery_play_mode = local[@"gallery_play_mode"];
                nullToNil(gallery_play_mode);
                //BOOL gallery_play_mode_auto = [gallery_play_mode isEqualToString:@"auto_scroll"];
                NSString* gallery_interval_ms = local[@"gallery_interval_ms"];
                nullToNil(gallery_interval_ms);
                //CGFloat gallery_interval = [gallery_interval_ms longLongValue]/1000.0f;
                
                if (!status_valid)needTapEvent_Scale = YES;
                if (status_valid) {
                    rectview.hot_adv_type_local = hottype;
                    //链接 当前没有时间意义popup中走了
                    if ([hottype isEqualToString:@"http"]) {
                        needTapEvent = YES;
                        needTapEvent_Scale = YES;
                    }
                    
                    //视频 当前没有时间意义popup中走了
                    else if ([hottype isEqualToString:@"video"]) {
                        needTapEvent = YES;
                        needTapEvent_Scale = YES;
                    }
                    
                    //图片模式
                    else if ([hottype isEqualToString:@"img"]) {
                        if (source && source.count > 0) {
                            NSString* uri = source.firstObject;
                            nullToNil(uri);
                            NSString* file =  [DataProcessing bookPathForBookID:self.bookid subDir:uri];
                            //NSString* fileTo = [file stringByAppendingString:@".png"];
                            NSData* imageData = nil;
                            if (needDecode) {
                                //BOOL ret = [WYCryptDES decryptFile:file toFile:fileTo withKey:__WYDEC_Code];
                                //if(ret){
                                //    imageData = [[NSData alloc] initWithContentsOfFile:fileTo];
                                //}
                                //[[NSFileManager defaultManager] removeItemAtPath:fileTo error:nil];
                                imageData = [[NSData alloc] initWithContentsOfFile:file];
                                imageData = [WYCryptDES decryptFileData:imageData key:__WYDEC_Code];
                            }else{
                                imageData = [[NSData alloc] initWithContentsOfFile:file];
                            }
                            
                            //图片处理
                            if (imageData) {
                                UIImage* image = [[UIImage alloc] initWithData:imageData scale:2.0];
                                CGFloat ratio = [DataProcessing shareSingle].ratio_w;
                                
                                //1:1模式
                                if (mode1_1) {
                                    UIImageView* igv = [[UIImageView alloc] initWithImage:image];
                                    CGRect frame = igv.frame;
                                    frame.size.width = floor(frame.size.width / ratio);
                                    frame.size.height = floor(frame.size.height / ratio);
                                    igv.frame = frame;
                                    igv.userInteractionEnabled = YES;
                                    PageImageScrollView* scrollview = [[PageImageScrollView alloc] initWithFrame:rectview.bounds];
                                    scrollview.showsHorizontalScrollIndicator = NO;
                                    scrollview.showsVerticalScrollIndicator = NO;
                                    scrollview.bounces = NO;
                                    scrollview.contentSize = frame.size;
                                    [scrollview addSubview:igv];
                                    [rectview addSubview:scrollview];
                                    
                                    //处理图片滚动示意标签
                                    NSString* rollType = [self addHostArea_adv_Img_Sign:scrollview];
                                    //
                                    needTapEvent = NO;
                                    //是否需要模态引导
                                    if ([self isNeedModelAlterWithModelType:hottype] && rollType) {
                                        rectview.modelType = [NSString stringWithFormat:@"%@_%@",hottype,rollType];
                                    }
                                }
                                
                                //全屏模式
                                else{
                                    UIImageView* igv = [[UIImageView alloc] initWithFrame:rectview.frame];
                                    igv.image = image;
                                    [_hotView addSubview:igv];
                                    //
                                    needTapEvent = YES;
                                    needTapEvent_Scale = YES;
                                }
                            }
                        }
                    }
                    
                    //Html5
                    else if ([hottype isEqualToString:@"h5"]) {
                        NSString* uri = source.firstObject;
                        nullToNil(uri);
                        NSString* file =  [DataProcessing bookPathForBookID:self.bookid subDir:uri];
                        NSString* fileTo = [file stringByAppendingString:@".html"];
                        NSData* h5Data = nil;
                        if (needDecode) {
                            //BOOL ret = [WYCryptDES decryptFile:file toFile:fileTo withKey:__WYDEC_Code];
                            //if(ret){
                            //    h5Data = [[NSData alloc] initWithContentsOfFile:fileTo];
                            //}
                            //[[NSFileManager defaultManager] removeItemAtPath:fileTo error:nil];
                            h5Data = [[NSData alloc] initWithContentsOfFile:file];
                            h5Data = [WYCryptDES decryptFileData:h5Data key:__WYDEC_Code];
                        }else{
                            h5Data = [[NSData alloc] initWithContentsOfFile:file];
                        }
                        
                        if (h5Data) {
                            UIWebView* webView = [[UIWebView alloc] initWithFrame:rectview.bounds];
                            webView.mediaPlaybackRequiresUserAction = NO;
                            webView.allowsInlineMediaPlayback = YES;
                            [rectview addSubview:webView];
                            webView.delegate = self;
                            webView.scrollView.showsHorizontalScrollIndicator = NO;
                            webView.scrollView.showsVerticalScrollIndicator = NO;
                            webView.tag = __PageWebViewTag_contentH5;
                            webView.opaque = NO;
                            webView.backgroundColor = [UIColor clearColor];
                            NSString* fileBase = [fileTo stringByDeletingLastPathComponent];
                            [webView loadData:h5Data MIMEType:@"text/html" textEncodingName:@"UTF-8" baseURL:[NSURL fileURLWithPath:fileBase]];
                            //
                            needTapEvent = NO;
                        }
                    }
                    
                    //轮播图片
                    else if ([hottype isEqualToString:@"gallery"]) {
                        if (source && source.count > 0) {
                            //是否需要模态引导
                            if ([self isNeedModelAlterWithModelType:hottype]) {
                                rectview.modelType = hottype;
                            }
                            PageImageScrollView* scrollview = [[PageImageScrollView alloc] initWithFrame:rectview.bounds];
                            scrollview.showsHorizontalScrollIndicator = NO;
                            scrollview.showsVerticalScrollIndicator = NO;
                            scrollview.bounces = NO;
                            scrollview.contentSize = CGSizeMake(rectview.bounds.size.width*source.count, rectview.bounds.size.height);
                            scrollview.pagingEnabled = YES;
                            if([@"valid" isEqualToString:popup[@"status"]]) scrollview.tapForNext = NO;
                            else scrollview.tapForNext = YES;
                            [rectview addSubview:scrollview];
                            rectview.gallerrySV = scrollview;
                            needTapEvent = NO;
                            //
                            for (int i=0; i<source.count; i++) {
                                NSString* uri = source[i];
                                nullToNil(uri);
                                NSString* file =  [DataProcessing bookPathForBookID:self.bookid subDir:uri];
                                //NSString* fileTo = [file stringByAppendingString:@".png"];
                                NSData* imageData = nil;
                                if (needDecode) {
                                    //BOOL ret = [WYCryptDES decryptFile:file toFile:fileTo withKey:__WYDEC_Code];
                                    //if(ret){
                                    //    imageData = [[NSData alloc] initWithContentsOfFile:fileTo];
                                    //}
                                    //[[NSFileManager defaultManager] removeItemAtPath:fileTo error:nil];
                                    imageData = [[NSData alloc] initWithContentsOfFile:file];
                                    imageData = [WYCryptDES decryptFileData:imageData key:__WYDEC_Code];
                                }else{
                                    imageData = [[NSData alloc] initWithContentsOfFile:file];
                                }
                                CGRect frame = scrollview.bounds;
                                frame.origin = CGPointMake(frame.size.width*i, 0);
                                UIImageView* imgv = [[UIImageView alloc] initWithFrame:frame];
                                imgv.image = [UIImage imageWithData:imageData];
                                [scrollview addSubview:imgv];
                                [scrollview addPanForScrollView];
                                //
                                ReadPageDot* pdot = [[ReadPageDot alloc] initWithFrame:CGRectMake(rectview.left, rectview.bottom, rectview.width,20/[DataProcessing shareSingle].ratio_w)];
                                [_hotView addSubview:pdot];
                                pdot.count = source.count;
                                pdot.wh_value = 12/[DataProcessing shareSingle].ratio_w;
                                pdot.imageCurrent = [UIImage imageNamed:@"page_icon_dot_black.png"];
                                pdot.imageNormal = [UIImage imageNamed:@"page_icon_dot_white.png"];
                                [pdot updateToIndex:0];
                                [pdot autoChangeSign_For:scrollview];
                            }
                        }
                    }
                }
                
                //icon状态，用户
                if (helper && helper.count > 0) {
                    NSString* status = helper[@"status"];
                    nullToNil(status);
                    //是否需要模态引导
                    NSString* modelType = helper[@"default_img"];
                    if ([modelType isEqualToString:@"None"]) {
                        NSArray* source = popup[@"source"];
                        nullToNil(source);
                        NSDictionary* firstSource = [source firstObject];
                        nullToNil(firstSource);
                        modelType = firstSource[@"type"];
                    }
                    if ([self isNeedModelAlterWithModelType:modelType]) {
                        rectview.modelType = modelType;
                    }
                    if (helper && [status isEqualToString:@"valid"]) {
                        rect = [self getRect:[helper objectForKey:@"rect"]];
                        w = rect.size.width;
                        h = rect.size.height;
                        x = rect.origin.x;
                        y = rect.origin.y;
                        //
                        NSString* urimg = helper[@"img"];
                        nullToNil(urimg);
                        NSString* file =  [DataProcessing bookPathForBookID:self.bookid subDir:urimg];
                        UIImage* image = nil;
                        if (file) {
                            image = [[UIImage alloc] initWithContentsOfFile:file];
                        }
                        //
                        if (!image) {
                            NSString* default_img = helper[@"default_img"];
                            nullToNil(default_img);
                            if ([@"Video" isEqualToString:default_img]) {
                                image = [UIImage imageNamed:@"page_btn_begin_normal.png"];
                            }else if ([@"Zoom" isEqualToString:default_img]) {
                                image = [UIImage imageNamed:@"page_btn_search_normal.png"];
                            }else if ([@"Info" isEqualToString:default_img]) {
                                image = [UIImage imageNamed:@"page_btn_read_normal.png"];
                            }else if ([@"Gallery" isEqualToString:default_img]) {
                                image = [UIImage imageNamed:@"page_btn_read_normal.png"];
                            }else if ([@"H5" isEqualToString:default_img]) {
                                image = [UIImage imageNamed:@"page_btn_h5_normal.png"];
                            }else if ([@"RolePlay" isEqualToString:default_img]) {
                                image = [UIImage imageNamed:@"page_btn_role_play.png"];
                            }
                            else if ([@"Audio" isEqualToString:default_img]) {
                                NSString* audio_style = helper[@"audio_style"];
                                nullToNil(audio_style);
                                //按钮样式 默认
                                image = [UIImage imageNamed:@"page_btn_suona1.png"];
                            }
                        }
                        UIImageView* igv = [[UIImageView alloc] initWithFrame:CGRectMake(x, y, w, h)];
                        igv.image = image;
                        [_hotView addSubview:igv];
                        rectview.helperIcon = igv;
                        rectview.helperIcon_popHide = [@"valid" isEqualToString:helper[@"hide_when_popup"]];
                    }
                }
                
            }
            
            //关闭不同类型的Tap控制
            needTapEvent = YES;
            if (needTapEvent) {
                //
                rectview.hot_adv_popup = popup;
                //tap
                UITapGestureRecognizer_SEL * tap = [[UITapGestureRecognizer_SEL alloc] initWithTarget:self action:@selector(tapHot_adv:)];
                tap.numberOfTouchesRequired = 1;
                tap.numberOfTapsRequired = 1;
                [rectview addGestureRecognizer:tap];
                if(needTapEvent_Scale)tap.delegate = [TLGestureRecognizerDelegate shareSingleTapView];
                tap.rippleColor = __BaseBackColor;
                [tap addTapRipple];
                if ([dict[@"local"][@"type"] isEqualToString:@"autoscale"]) {
                    //
                    UITapGestureRecognizer_SEL * doubleTap = [[UITapGestureRecognizer_SEL alloc] initWithTarget:self action:@selector(handleDoubleTap:)];
                    doubleTap.numberOfTapsRequired = 2;
                    doubleTap.numberOfTouchesRequired = 1;
                    [rectview addGestureRecognizer:doubleTap];
                    [tap requireGestureRecognizerToFail:doubleTap];
                    //双指
                    UITapGestureRecognizer_SEL * twoFingerTap = [[UITapGestureRecognizer_SEL alloc] initWithTarget:self action:@selector(handleDoubleTap:)];
                    twoFingerTap.numberOfTouchesRequired = 2;
                    twoFingerTap.numberOfTapsRequired = 1;
                    [rectview addGestureRecognizer:twoFingerTap];
                    [tap requireGestureRecognizerToFail:twoFingerTap];
                }
            }
            //热区模态提醒数据整合
            if (rectview.modelType) {
                [alertRectViewArray addObject:rectview];
            }
            //
            [_hotView addSubview:rectview];
            //
            //
            //debug
            //rectview.layer.borderWidth = 1;
            //rectview.layer.borderColor = [[UIColor blueColor] colorWithAlphaComponent:0.6].CGColor;
        }
    }
    self.alertRectViewArray = alertRectViewArray;
}
//确定是否是需要模态引导的类型
-(BOOL)isNeedModelAlterWithModelType:(NSString*)modelType{
    BOOL isNeed = NO;
    if ([modelType isEqualToString:@"img"] ||
        [modelType isEqualToString:@"gallery"] ||
        [modelType isEqualToString:@"Video"] ||
        [modelType isEqualToString:@"Zoom"] ||
        [modelType isEqualToString:@"Info"]||
        [modelType isEqualToString:@"H5"] ||
        [modelType isEqualToString:@"Audio"] ||
        [modelType isEqualToString:@"http"]) {
        //
        isNeed = YES;
    }
    return isNeed;
}

- (void)addHostAreaBtns
{
    NSDictionary* region = [pageDict objectForKey:@"region"];
    nullToNil(region);
    NSArray* hot_area = [region objectForKey:@"hot_area"];
    nullToNil(hot_area);
    //
    if (hot_area && hot_area.count > 0) {
        for (NSDictionary* dic in hot_area) {
            CGRect rect = [self getRect:[dic objectForKey:@"rect"]];
            CGFloat w = rect.size.width;
            CGFloat h = rect.size.height;
            CGFloat x = rect.origin.x;
            CGFloat y = rect.origin.y;
            //
            KoK_RectView* rectview = [[KoK_RectView alloc] initWithFrame:CGRectMake(x, y, w, h)];
            rectview.isHot_Area = YES;
            rectview.source = dic[@"source"];
            rectview.action = dic[@"action"];
            [_hotView addSubview:rectview];
            //
            //tap
            UITapGestureRecognizer_SEL * tap = [[UITapGestureRecognizer_SEL alloc] initWithTarget:self action:@selector(tapHot:)];
            [rectview addGestureRecognizer:tap];
            tap.delegate = [TLGestureRecognizerDelegate shareSingleTapView];
            tap.rippleColor = __BaseBackColor;
            [tap addTapRipple];
            //
            //debug
            //rectview.layer.borderWidth = 1;
            //rectview.layer.borderColor = [[UIColor greenColor] colorWithAlphaComponent:0.6].CGColor;
        }
    }
}

- (void)addSubReadBtns
{
    NSDictionary* region = [pageDict objectForKey:@"region"];
    nullToNil(region);
    NSArray* sread = [region objectForKey:@"sread"];
    nullToNil(sread);
    //
    if (sread && sread.count > 0) {
        for (NSDictionary* dic in sread) {
            NSNumber* iconsize = dic[@"icon_size"];
            NSNumber* cx = dic[@"center_x"];
            NSNumber* cy = dic[@"center_y"];
            NSArray* index = dic[@"index"];
            nullToNil(iconsize);
            nullToNil(cx);
            nullToNil(cy);
            nullToNil(index);
            if (cx && cy && index && index.count > 0) {
                int isize = 100;
                if(iconsize && iconsize.intValue <= 0){
                    isize = 1;
                }else if(iconsize && iconsize.intValue > 200){
                    isize = 200;
                }
                StatusButton_2_View* sreadBtn = [self newPlayStatusBtn_scale:isize/100.0];
                sreadBtn.center = CGPointMake(cx.floatValue*self.bookRatioWH, cy.floatValue*self.bookRatioWH);
                sreadBtn.userInfo = @{@"index":index};
                [_hotView addSubview:sreadBtn];
                [SReadBtnMArr addObject:sreadBtn];
            }
        }
    }
}

- (void)addSubRead_adv_Btns
{
    NSDictionary* region = [pageDict objectForKey:@"region"];
    nullToNil(region);
    NSDictionary* sread_adv = [region objectForKey:@"sread_adv"];
    nullToNil(sread_adv);
    //
    if (sread_adv && sread_adv.count > 0) {
        //
        NSArray* paragraph = sread_adv[@"paragraph"];
        NSNumber* paragraph_suffix = sread_adv[@"paragraph_suffix"];
        NSArray* article = sread_adv[@"article"];
        NSNumber* article_suffix = sread_adv[@"article_suffix"];
        nullToNil(paragraph);
        nullToNil(paragraph_suffix);
        nullToNil(article);
        nullToNil(article_suffix);
        _paragraph_suffix = [paragraph_suffix boolValue];
        _article_suffix = [article_suffix boolValue];
        //
        [paragraph enumerateObjectsUsingBlock:^(NSDictionary*  _Nonnull dic, NSUInteger idx, BOOL * _Nonnull stop) {
            NSArray* index = dic[@"sentence"];
            NSString* type = dic[@"type"];
            NSString* icon_rect = dic[@"icon_rect"];
            nullToNil(index);
            nullToNil(type);
            nullToNil(icon_rect);
            CGRect rect = [self getRect:icon_rect];
            StatusButton_2_View* sreadBtn = nil;
            if ([self.readSource isEqualToString:ReadSource_JR]) {
                sreadBtn = [self newPlayStatusBtn_frame:rect]; //蓝色按钮
            }else{
                sreadBtn = [self newPepPlayStatusBtn_frame:rect]; //灰色按钮
            }
            if (_paragraph_suffix && idx == paragraph.count-1) {
                sreadBtn.userInfo = @{@"index":index?index:@[],@"type":@"paragraph",@"paragraph_suffix":@(1)};
            }else{
                sreadBtn.userInfo = @{@"index":index?index:@[],@"type":@"paragraph"};
            }
            [_hotView addSubview:sreadBtn];
            sreadBtn.tag = SreadBtn_TAG_Paragraph;
            [SReadBtnMArr addObject:sreadBtn];
            sreadBtn.hidden = YES;
            if ([type isEqualToString:@"normal"]) {
                sreadBtn.hidden = NO;
            }else if([type isEqualToString:@"prev_suffix"]){
                _paragraph_prev_suffix_index = index;
                NSMutableDictionary* mdict = [NSMutableDictionary dictionaryWithDictionary:sreadBtn.userInfo];
                [mdict setObject:@(1) forKey:@"paragraph_prev_suffix"];
                [mdict setObject:@(1) forKey:@"prev_suffix"];
                sreadBtn.userInfo = mdict;
            }
        }];
        [article enumerateObjectsUsingBlock:^(NSDictionary*  _Nonnull dic, NSUInteger idx, BOOL * _Nonnull stop) {
            NSArray* index = dic[@"sentence"];
            NSString* type = dic[@"type"];
            NSString* icon_rect = dic[@"icon_rect"];
            nullToNil(index);
            nullToNil(type);
            nullToNil(icon_rect);
            CGRect rect = [self getRect:icon_rect];
            StatusButton_2_View* sreadBtn = nil;
            if ([self.readSource isEqualToString:ReadSource_JR]) {
                sreadBtn = [self newPlayStatusBtn_frame:rect]; //蓝色按钮
            }else{
                sreadBtn = [self newPepPlayStatusBtn_frame:rect]; //灰色按钮
            }
            if (_article_suffix && idx == article.count-1) {
                sreadBtn.userInfo = @{@"index":index?index:@[],@"type":@"article",@"article_suffix":@(1)};
            }else{
                sreadBtn.userInfo = @{@"index":index?index:@[],@"type":@"article"};
            }
            [_hotView addSubview:sreadBtn];
            sreadBtn.tag = SreadBtn_TAG_Article;
            [SReadBtnMArr addObject:sreadBtn];
            sreadBtn.hidden = YES;
            if ([type isEqualToString:@"normal"]) {
                sreadBtn.hidden = NO;
            }else if([type isEqualToString:@"prev_suffix"]){
                _article_prev_suffix_index = index;
                NSMutableDictionary* mdict = [NSMutableDictionary dictionaryWithDictionary:sreadBtn.userInfo];
                [mdict setObject:@(1) forKey:@"article_prev_suffix"];
                [mdict setObject:@(1) forKey:@"prev_suffix"];
                sreadBtn.userInfo = mdict;
            }
        }];
    }
}

- (void)addRectForWord
{
    NSDictionary* region = [pageDict objectForKey:@"region"];
    nullToNil(region);
    trans = [region objectForKey:@"trans"];
    nullToNil(trans);
    if (trans && trans.length >0)_hasTrans = YES;
    NSArray* sentenceArr = [region objectForKey:@"sentence"];
    nullToNil(sentenceArr);
    NSMutableArray* showTextArray = [NSMutableArray new];
    NSMutableArray* ASRTextArray = [NSMutableArray new];
    NSMutableArray* textLangArray = [NSMutableArray new];
    [sentenceArr enumerateObjectsUsingBlock:^(NSDictionary*  _Nonnull dict, NSUInteger idx, BOOL * _Nonnull stop) {
        [textLangArray addObject:@(btype)];
        //for (NSDictionary* dict in sentenceArr) {
        NSDictionary* gotopage = [dict objectForKey:@"gotopage"];
        nullToNil(gotopage);
        NSDictionary* prev = [gotopage objectForKey:@"prev"];
        nullToNil(prev);
        NSDictionary* next = [gotopage objectForKey:@"next"];
        nullToNil(next);
        //
        NSDictionary* voice = [dict objectForKey:@"voice"];
        nullToNil(voice);
        NSString* mp3 = [voice objectForKey:@"mp3"];
        nullToNil(mp3);
        if(mp3 && mp3.length >0){
            NSString* idxKey = @(mp3Arr.count).description;
            if (prev != nil) {
                GoToPage* go = [GoToPage new];
                go.type = GoToPageType_prev;
                go.offset = [prev[@"offset"] integerValue];
                go.index = [prev[@"target_index"] integerValue];
                [dict_prevGoToPage setObject:go forKey:idxKey];
            }
            if (next != nil) {
                GoToPage* go = [GoToPage new];
                go.type = GoToPageType_next;
                go.offset = [next[@"offset"] integerValue];
                go.index = [next[@"target_index"] integerValue];
                [dict_nextGoToPage setObject:go forKey:idxKey];
            }
            [mp3Arr addObject:mp3];
        }
        //
        NSMutableArray* mArr_setence = [[NSMutableArray alloc] initWithCapacity:0];
        [kok_RectViewArr_sentence addObject:mArr_setence];
        //
        NSArray* points = [voice objectForKey:@"points"];
        NSArray* cutTexts = [dict objectForKey:@"cut_text"];
        NSArray* subRects = [dict objectForKey:@"sub_rect"];
        nullToNil(points);
        nullToNil(cutTexts);
        nullToNil(subRects);
        NSInteger count_Points = 0;
        NSInteger count_cutTexts = 0;
        NSInteger repeat = 0;
        NSInteger count_repeat = 0;
        if(points.count==0){
#if __Debug_BooksFileReading
            NSLog(@"不存在打点数据");
#endif
        }
        //扩展英文书，phrease_idx数据
        int phrease_count = 0;
        NSMutableArray* phreaseArr = [NSMutableArray new];
        //
        NSMutableArray* showTextArray_one = [NSMutableArray new];
        NSMutableArray* ASRTextArray_one = [NSMutableArray new];
        if(cutTexts.count ==0){
#if __Debug_BooksFileReading
            NSLog(@"不存在取词数据");
#endif
        }else{
            for (int i=0; i< cutTexts.count; i++) {
                NSString* keywd =  cutTexts[i][@"wd"];
                NSString* py = cutTexts[i][@"py"];
                [phreaseArr addObject:keywd];
                if (![keywd isEqualToString:@"%"] && ![DataProcessing isFullWidthNumber:keywd]) {
                    //显示
                    if (btype == 0) {
                        [showTextArray_one addObject:keywd];
                    }else{
                        [showTextArray_one addObject:[NSString stringWithFormat:@"%@ ",keywd]];
                    }
                    //评测
                    if ([py isEqualToString:@""]) {
                        if (i == cutTexts.count - 1) {
                            [ASRTextArray_one addObject:py];
                        }else{
                            [ASRTextArray_one addObject:@" "];
                        }
                    }else{
                        if (btype == 0) {
                            [ASRTextArray_one addObject:keywd];
                        }else{
                            [ASRTextArray_one addObject:[NSString stringWithFormat:@"%@ ",keywd]];
                        }
                    }
                }
            }
            if (showTextArray_one.count > 0 && ASRTextArray_one.count > 0 && mp3.length > 0) {
                [showTextArray addObject:showTextArray_one];
                [ASRTextArray addObject:ASRTextArray_one];
            }
        }
        //
        for (NSInteger lineIndex=0; lineIndex < subRects.count; lineIndex++ ) {
            NSDictionary* sdic = subRects[lineIndex];
            @autoreleasepool {
                NSArray* rect = [DataProcessing getNumbersFromString:[sdic objectForKey:@"rect"]];
                NSArray* lines = [DataProcessing getNumbersFromString:[sdic objectForKey:@"lines"]];
                if (rect.count != 4) {
                    rect = @[@(0),@(0),@(0),@(0)];
                }
                CGFloat w = [rect[2] floatValue] -[rect[0] floatValue];
                CGFloat h = [rect[3] floatValue] -[rect[1] floatValue];
                CGFloat x = [rect[0] floatValue];
                CGFloat y = [rect[1] floatValue];
                if (lines) {
                    CGFloat lastX = x;
                    CGRect frame;
                    for (int i = 0; i<=lines.count; i++) {
                        CGFloat px = w+x;
                        if (i<lines.count) {
                            px = [[lines objectAtIndex:i] floatValue]+x;
                        }
                        frame = CGRectMake(lastX*self.bookRatioWH, y*self.bookRatioWH, (px-lastX)*self.bookRatioWH, h*self.bookRatioWH);
                        KoK_RectView* rectview = [[KoK_RectView alloc] initWithFrame:frame];
                        rectview.center_25x = CGPointMake(rectview.center.x-frame.size.width*self.bookRatioWH/4, rectview.center.y);
                        rectview.center_75x = CGPointMake(rectview.center.x+frame.size.width*self.bookRatioWH/4, rectview.center.y);
                        rectview.center_25y = CGPointMake(rectview.center.x, rectview.center.y-h*self.bookRatioWH/4);
                        rectview.center_75y = CGPointMake(rectview.center.x, rectview.center.y+h*self.bookRatioWH/4);
                        [mArr_setence addObject:rectview];
                        [_hotView addSubview:rectview];
#if __Debug_KoK_rect
                        [rectview addBorders];
#endif
                        lastX = px;
                        //打点数据
                        NSDictionary* pointDic = nil;
                        if (points.count > count_Points) {
                            pointDic = [points objectAtIndex:count_Points];
                        }else{
                            if(points.count>0)NSLog(@"打点数据不匹配 %d",(int)count_Points);
                        }
                        while ( notNULL([pointDic objectForKey:@"wd"]) && [[pointDic objectForKey:@"wd"] isEqualToString:@""]) {
                            count_Points++;
                            if (count_Points >= points.count) {
                                break;
                            }
                            pointDic = [points objectAtIndex:count_Points];
                        }
                        NSString* wd = [pointDic objectForKey:@"wd"];
                        nullToNil(wd);
                        rectview.word = wd;
                        NSNumber* number = [pointDic objectForKey:@"bg"];
                        nullToNil(number);
                        rectview.biganMS = [number longLongValue];
                        number = [pointDic objectForKey:@"ed"];
                        nullToNil(number);
                        rectview.endMS = [number longLongValue];
                        count_Points++;
                        //MP3 index
                        rectview.mp3_Index = (NSInteger)idx;
                        
                        //GoToPage
                        rectview.goPage = dict_prevGoToPage[@(idx).description];
                        if (i >= lines.count && lineIndex == subRects.count-1) { //lines.count -1 去掉，不能再兼容数据打点错误的问题
                            GoToPage* gopage = dict_nextGoToPage[@(idx).description];
                            if(gopage)rectview.goPage = gopage;
                        }
                        
                        //取词数据
                        NSDictionary* textDic = nil;
                        if (cutTexts.count > count_cutTexts) {
                            textDic = [cutTexts objectAtIndex:count_cutTexts];
                        }else{
                            if(cutTexts.count>0)NSLog(@"取词数据不匹配 %d",(int)count_cutTexts);
                        }
                        NSString* kw = [textDic objectForKey:@"wd"];
                        nullToNil(kw);
                        rectview.keyWord = kw;
                        NSString* kwpy = [textDic objectForKey:@"py"];
                        nullToNil(kwpy);
                        rectview.keyWordPinyin = kwpy;
                        //
                        rectview.phrase = phreaseArr;
                        rectview.phrease_idx = phrease_count;
                        phrease_count++;
                        //
                        count_cutTexts++;
                        if (repeat == 0) {
                            NSInteger numberWord = rectview.keyWord.length;
                            repeat = numberWord-1;
                            if(btype!=0){
                                NSArray* wordsArr = [rectview.keyWord componentsSeparatedByString:@" "];//一个空格区分单词
                                if (wordsArr.count >1)repeat = wordsArr.count-1;
                                else repeat = 0;
                            }
                        }
                        if (repeat > 0) {
                            count_repeat++;
                            if (count_repeat == repeat+1) {
                                repeat  = count_repeat = 0;
                            }else{
                                count_cutTexts--;
                            }
                        }
                        
                        //tap
                        UITapGestureRecognizer_SEL * tap = [[UITapGestureRecognizer_SEL alloc] initWithTarget:self action:@selector(tap:)];
                        [rectview addGestureRecognizer:tap];
                        tap.delegate = [TLGestureRecognizerDelegate shareSingleTapView];
                        tap.rippleColor = __BaseBackColor;
                        [tap addTapRipple];
                    }
                }
            }
        }
        //}
    }];
    if (![ReadBookVOrH_VC currentReadInstance].evaluateDict) {
        self.showTextArray = showTextArray;
        self.ASRTextArray = ASRTextArray;
        self.textLangArray = textLangArray;
        self.mp3PathArray = mp3Arr;
    }
}

//准备语音评测的数据
-(void)readyEvaluateData{
    NSDictionary* evaluateDict = [ReadBookVOrH_VC currentReadInstance].evaluateDict;
    NSMutableArray* showTextArray = [NSMutableArray new];
    NSMutableArray* ASRTextArray = [NSMutableArray new];
    NSMutableArray* textLangArray = [NSMutableArray new];
    NSMutableArray* mp3PathArray = [NSMutableArray new];
    NSArray* onePageArray = evaluateDict[self.nameFolder];
    for (NSDictionary* oneWordDict in onePageArray) {
        NSString* lang = oneWordDict[@"lang"];
        NSString* ASRWord = oneWordDict[@"cut_text_cn"];
        if ([lang isEqualToString:@"en"]) {
            ASRWord = oneWordDict[@"cut_text_en"];
            ASRWord = [ASRWord stringByReplacingOccurrencesOfString:@"||" withString:@"| |"];
        }
        NSArray* ASRWordArray = [ASRWord componentsSeparatedByString:@"|"];
        //
        NSString* showText = oneWordDict[@"cut_text_show"];
        NSArray* showWordArray = [showText componentsSeparatedByString:@"|"];
        //
        NSString* mp3Path = oneWordDict[@"mp3"];
        if (ASRWordArray.count > 0 && showWordArray.count > 0 && mp3Path.length > 0) {
            [ASRTextArray addObject:ASRWordArray];
            [showTextArray addObject:showWordArray];
            [mp3PathArray addObject:mp3Path];
            if ([lang isEqualToString:@"cn"]) {
                [textLangArray addObject:@(0)];
            }else if ([lang isEqualToString:@"en"]){
                [textLangArray addObject:@(1)];
            }
        }
    }
    self.showTextArray = showTextArray;
    self.ASRTextArray = ASRTextArray;
    self.textLangArray = textLangArray;
    self.mp3PathArray = mp3PathArray;
}


- (void)addBgImageWithArr:(NSArray*)arr withSuperView:(UIView*)view;
{
    for (NSDictionary* dict in arr) {
        @autoreleasepool {
            NSNumber* ltx = [dict objectForKey:@"ltx"];
            NSNumber* lty = [dict objectForKey:@"lty"];
            NSNumber* lw = [dict objectForKey:@"w"];
            NSNumber* lh = [dict objectForKey:@"h"];
            nullToNil(ltx);
            nullToNil(lty);
            nullToNil(lw);
            nullToNil(lh);
            CGFloat x = [ltx floatValue];
            CGFloat y = [lty floatValue];
            CGFloat w = [lw floatValue];
            CGFloat h = [lh floatValue];
            NSString* uri = [dict objectForKey:@"uri"];
            nullToNil(uri);
            CGRect frame = CGRectMake(x*self.bookRatioWH, y*self.bookRatioWH, w*self.bookRatioWH, h*self.bookRatioWH);
            UIImageView* imgv = [[UIImageView alloc] initWithFrame:frame];
            NSString* file =  [DataProcessing bookPathForBookID:self.bookid subDir:uri];
            UIImage* image = [UIImage imageWithContentsOfFile:file];
            UIImage *scaledImage = [[UIImage alloc] initWithCGImage:image.CGImage scale:1 orientation:UIImageOrientationUp];
            //        image = [image alphaEdgeWithPx:5];
            imgv.image = scaledImage;
            if(view)[view addSubview:imgv];
            else [contentView addSubview:imgv];
        }
    }
}

- (void)addImageWithArr:(NSArray*)arr withSuperView:(UIView*)view;
{
    for (NSDictionary* dict in arr) {
        @autoreleasepool {
            NSNumber* ltx = [dict objectForKey:@"ltx"];
            NSNumber* lty = [dict objectForKey:@"lty"];
            NSNumber* lw = [dict objectForKey:@"w"];
            NSNumber* lh = [dict objectForKey:@"h"];
            nullToNil(ltx);
            nullToNil(lty);
            nullToNil(lw);
            nullToNil(lh);
            CGFloat x = [ltx floatValue];
            CGFloat y = [lty floatValue];
            CGFloat w = [lw floatValue];
            CGFloat h = [lh floatValue];
            NSString* uri = [dict objectForKey:@"uri"];
            nullToNil(uri);
            CGRect frame = CGRectMake(x*self.bookRatioWH, y*self.bookRatioWH, w*self.bookRatioWH, h*self.bookRatioWH);
            UIImageView* imgv = [[UIImageView alloc] initWithFrame:frame];
            NSString* file =  [DataProcessing bookPathForBookID:self.bookid subDir:uri];
            UIImage* image = [UIImage imageWithContentsOfFile:file];
            UIImage *scaledImage = [[UIImage alloc] initWithCGImage:image.CGImage scale:1 orientation:UIImageOrientationUp];
            imgv.image = scaledImage;
            if(view)[view addSubview:imgv];
            else [contentView addSubview:imgv];
        }
    }
}

- (void)add_KOK_ImageWithArrr:(NSArray*)arr
{
    for (NSDictionary* dict in arr) {
        @autoreleasepool {
            NSNumber* ltx = [dict objectForKey:@"ltx"];
            NSNumber* lty = [dict objectForKey:@"lty"];
            NSNumber* lw = [dict objectForKey:@"w"];
            NSNumber* lh = [dict objectForKey:@"h"];
            nullToNil(ltx);
            nullToNil(lty);
            nullToNil(lw);
            nullToNil(lh);
            CGFloat x = [ltx floatValue];
            CGFloat y = [lty floatValue];
            CGFloat w = [lw floatValue];
            CGFloat h = [lh floatValue];
            NSString* uri = [dict objectForKey:@"uri"];
            nullToNil(uri);
            CGRect frame = CGRectMake(0, 0, w*self.bookRatioWH, h*self.bookRatioWH);
            UIImageView* imgv = [[UIImageView alloc] initWithFrame:frame];
            NSString* file =  [DataProcessing bookPathForBookID:self.bookid subDir:uri];
            UIImage* image = [UIImage imageWithContentsOfFile:file];
            UIColor* kokcolor =  self.kokColor;
            if (!kokcolor) {
                kokcolor = [UIColor redColor];
            }
            CGFloat red, green, blue, al; //卡拉ok 不着色
            if ([kokcolor getRed:&red green:&green blue:&blue alpha:&al]) {
                if (al > 0.01) {
                    image = [image changeAllColo_RGB_toUicolor:kokcolor];
                    //image = [UIImage changeImage:image allColo_RGB_toUicolor:kokcolor];
                    UIImage *scaledImage = [[UIImage alloc] initWithCGImage:image.CGImage scale:1 orientation:UIImageOrientationUp];
                    imgv.image = scaledImage;
                }else{
                    imgv.image = nil;
                }
            }
            //
            frame.origin.x = x*self.bookRatioWH;
            frame.origin.y = y*self.bookRatioWH;
            frame.size.width = 0;
            KoK_ClipView* clipView = [[KoK_ClipView alloc] initWithFrame:frame];
            [clipView addSubview:imgv];
            clipView.clipsToBounds = YES;
            [kok_ClipViewArr addObject:clipView];
            frame.size.width = w*self.bookRatioWH;
            clipView.frameFull = frame;
            //
            [kok_View addSubview:clipView];
        }
    }
}

- (void)tapHot_adv:(UITapGestureRecognizer_SEL*)tp
{
    [self anyTapGesWithTapGesture:tp];
    //[((ReadView*)self.tapCallBackDelegate) performSelector:@selector(didPageViewTapRect_Hot_adv:) withObject:tp];
    [NSObject msgToTarget:self.tapCallBackDelegate menthed:@"didPageViewTapRect_Hot_adv:" refs:@[tp] needReturnValue:NO];
}

//判断单击事件
- (void)anyTapGesWithTapGesture:(UITapGestureRecognizer_SEL*)tap_sel{
    UIView* superView = tap_sel.view.superview;
    if (tap_sel.numberOfTapsRequired == 1 && tap_sel.numberOfTouchesRequired == 1) {
        NSArray* subViewsArr = superView.subviews;
        [subViewsArr enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            KoK_RectView* subView = (KoK_RectView*)obj;
            if (subView.userInteractionEnabled && CGRectContainsPoint(subView.frame, [tap_sel locationInView:superView]) && !subView.isScaleView) {
                NSArray* gesArray = subView.gestureRecognizers;
                for (UIGestureRecognizer* gesTure in gesArray) {
                    if ([gesTure isKindOfClass:[UITapGestureRecognizer_SEL class]]) {
                        UITapGestureRecognizer_SEL* gesTure_sel = (UITapGestureRecognizer_SEL*)gesTure;
                        [NSObject msgToTarget:gesTure_sel.target_sel menthed:gesTure_sel.selStr refs:@[gesTure_sel] needReturnValue:NO];
                    }
                }
            }
        }];
    }
}

- (void)tapHot:(UITapGestureRecognizer_SEL*)tp
{
    //[((ReadView*)self.tapCallBackDelegate) performSelector:@selector(didPageViewTapRect_Hot:) withObject:tp];
    [NSObject msgToTarget:self.tapCallBackDelegate menthed:@"didPageViewTapRect_Hot:" refs:@[tp] needReturnValue:NO];
}

- (void)tap:(UITapGestureRecognizer_SEL*)tp
{
    //[((ReadView*)self.tapCallBackDelegate) performSelector:@selector(didPageViewTapRect:) withObject:tp];
    [NSObject msgToTarget:self.tapCallBackDelegate menthed:@"didPageViewTapRect:" refs:@[tp] needReturnValue:NO];
}

- (void)click_talk
{
    //[((ReadView*)self.tapCallBackDelegate) performSelector:@selector(didPageViewClickedTalk) withObject:nil];
    [NSObject msgToTarget:self.tapCallBackDelegate menthed:@"didPageViewClickedTalk" refs:nil needReturnValue:NO];
}

- (void)addLoadingAnimationToView:(UIView*)view
{
    UIImage* image = [UIImage imageNamed:@"public_loading01.png"];
    UIImageView* imgvN = [[UIImageView alloc] init];
    imgvN.animationImages = [NSArray arrayWithObjects:image,[UIImage imageNamed:@"public_loading02.png"],[UIImage imageNamed:@"public_loading03.png"],[UIImage imageNamed:@"public_loading04.png"],[UIImage imageNamed:@"public_loading05.png"],[UIImage imageNamed:@"public_loading06.png"],[UIImage imageNamed:@"public_loading07.png"],[UIImage imageNamed:@"public_loading08.png"], nil];
    imgvN.animationDuration = 0.8f;
    imgvN.animationRepeatCount = 0;//forever
    [view addSubview:imgvN];
    imgvN.tag = __PageWebViewTag_loading;
    [imgvN startAnimating];
    imgvN.translatesAutoresizingMaskIntoConstraints = NO;
    [imgvN lyt_setSize:image.size];
    [imgvN lyt_centerInParent];
}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    NSString *requestString = [[request URL] absoluteString];
    NSArray *components = [requestString componentsSeparatedByString:@":"];
    if ([(NSString *)[components objectAtIndex:0] isEqualToString:@"localcall"]) {
        if([components count] > 1 && [(NSString *)[components objectAtIndex:1] isEqualToString:@"quitquiz"])
        {
            [[NSNotificationCenter defaultCenter] postNotificationName:@"quitquiz" object:nil];
        }
        return NO;
    }
    return YES;
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(addLoadingAnimationToView:) object:webView];
    [webView removeAllSubViews];
    //
    if (webView.tag == __PageWebViewTag_quiz) {
        UIImage* image = [UIImage imageNamed:@"public_quizfailed.png"];
        UIImageView* imgv = [[UIImageView alloc] initWithImage:image];
        [webView addSubview:imgv];
        imgv.translatesAutoresizingMaskIntoConstraints = NO;
        [imgv lyt_centerInParent];
        [imgv lyt_setSize:image.size];
    }
}

- (void)webViewDidStartLoad:(UIWebView *)webView
{
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(addLoadingAnimationToView:) object:webView];
    [self performSelector:@selector(addLoadingAnimationToView:) withObject:webView afterDelay:0.5];
}

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(addLoadingAnimationToView:) object:webView];
    UIView* imgvN = [webView viewWithTag:__PageWebViewTag_loading];
    if (imgvN) {
        [imgvN removeFromSuperview];
    }
    //
    NSString* title = [webView stringByEvaluatingJavaScriptFromString:@"document.title"];
    if (![title isEqualToString:@"Quiz"]) {
        [[RNCachingURLProtoclSetting getInstance] cleanCacheForUrl:[[[webView request] URL] absoluteString]];
        //NSLog(@"Quiz Load Error");
    }
    if (webView.tag == __PageWebViewTag_contentH5) {
        CGRect frame = webView.frame;
        CGRect frameTemp = frame;
        frame.size.height = 1;
        webView.frame = frame;
        frame.size.height = webView.scrollView.contentSize.height;
        //NSLog(@"frame = %@", [NSValue valueWithCGRect:frame]);
        webView.frame = frameTemp;
        webView.scrollView.contentSize = frame.size;
        //处理图片滚动示意标签
        [self addHostArea_adv_Img_Sign:webView.scrollView];
    }
}

#pragma mark - Zoom methods

- (void)handleDoubleTap:(UIGestureRecognizer *)gesture
{
    float newScale = ceil(zoomView.zoomScale) >= [self analyzedZoomNumberWith:gesture] ? 1 :[self analyzedZoomNumberWith:gesture];
    CGRect zoomRect = [self zoomRectForScale:newScale withCenter:gesture.view.center];
    [zoomView zoomToRect:zoomRect animated:YES];
}

//计算合适的放大倍数
-(CGFloat)analyzedZoomNumberWith:(UIGestureRecognizer *)gesture{
    CGFloat zoomScale = 1;
    CGFloat hotAreaWidth = gesture.view.width;
    CGFloat hotAreaHeight = gesture.view.height;
    CGFloat widthScale = (self.width - 60) / hotAreaWidth;
    CGFloat heightScale = (self.height - 60) / hotAreaHeight;
    if (widthScale > _max_scale && heightScale > _max_scale) {
        zoomScale = _max_scale;
    }else if (widthScale > heightScale){
        zoomScale = heightScale;
    }else if (widthScale < heightScale){
        zoomScale = widthScale;
    }
    return zoomScale;
}

//计算放大区域
- (CGRect)zoomRectForScale:(float)scale withCenter:(CGPoint)center
{
    CGRect zoomRect;
    zoomRect.size.height = self.frame.size.height / scale;
    zoomRect.size.width  = self.frame.size.width  / scale;
    zoomRect.origin.x = center.x - (zoomRect.size.width  / 2.0);
    zoomRect.origin.y = center.y - (zoomRect.size.height / 2.0);
    return zoomRect;
}


#pragma mark - UIScrollViewDelegate

- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
    return contentView;
}

- (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(CGFloat)scale
{
    [scrollView setZoomScale:scale animated:NO];
    [self scrollViewDidZoom:scrollView];
    //
    //telen 统计
    ReadView* read = self.tapCallBackDelegate;
    ReadBookVOrH_VC* rvc = (ReadBookVOrH_VC*)read.delegate;
    //[UMSAgent postEvent:@"Page_zoom" label:[NSString stringWithFormat:@"%@_%d",rvc.bookName,(int)self.pageIndex]];
    //[NSObject msgToClassName:@"UMSAgent" menthed:@"postEvent:label:" refs:@[@"Page_zoom",[NSString stringWithFormat:@"%@_%d",rvc.bookName,(int)self.pageIndex]] needReturnValue:NO];
}

- (void)scrollViewDidZoom:(UIScrollView *)scrollView
{
    BOOL seb = fabs(scrollView.zoomScale-1.0)<=0.01;
    UIScrollView* sv = (UIScrollView*)self.superview;
    sv.scrollEnabled = seb;
    //
    if (scrollView.zoomScale < 1.01) {
        UIView* spv = contentView.superview;
        contentView.center = CGPointMake(spv.frame.size.width*0.5, spv.frame.size.height*0.5);
    }
    //
    ReadView* read = self.tapCallBackDelegate;
    if (read.delegate && [read.delegate respondsToSelector:@selector(readViewPageDidZoom:)]) {
        [read.delegate readViewPageDidZoom:self];
    }
}

@end

#pragma mark- ReadView
@implementation ReadView
@synthesize pageScroll = scrollView;

- (PageView *)theNextPageView
{
    id next = nil;
    if (_currentPageView == pageCenter) {
        next = pageRight;
    }
    else if (_currentPageView == pageLeft) {
        next = pageCenter;
    }
    return next;
}

- (PageView *)thePrevPageView
{
    id prev = nil;
    if (_currentPageView == pageCenter) {
        prev = pageLeft;
    }
    else if (_currentPageView == pageRight){
        prev = pageCenter;
    }
    return prev;
}

- (void)dealloc
{
    self.kokColor = nil;
    self.pageList = nil;
#if __Debug_is_dealloced_log
    NSLog(@"dealloc: %@",NSStringFromClass([self class]));
#endif
}

- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        self.clipsToBounds = YES;
    }
    return self;
}

- (void)update_OutPage_CoverView
{
    if (leftCoverView && rightCoverView) {
        return;
    }
    CGRect frame = CGRectMake(-self.frame.origin.x, 0, self.frame.origin.x, self.frame.size.height);
    if (frame.size.width > 0) {
        scrollView.clipsToBounds = NO;
        self.clipsToBounds = NO;
        //
        if ([DataProcessing iOS7_low]) {
            UIImage* image = [UIImage imageNamed:@"bookcase_bg_cell.png"];
            //
            leftCoverView = [[UIView alloc] initWithFrame:frame];
            leftCoverView.backgroundColor = [UIColor colorWithPatternImage:image];
            leftCoverView.alpha = 0.90;
            [self addSubview:leftCoverView];
            //
            frame.origin.x += frame.size.width+self.frame.size.width;
            rightCoverView = [[UIView alloc] initWithFrame:frame];
            rightCoverView.backgroundColor = [UIColor colorWithPatternImage:image];
            rightCoverView.alpha = 0.90;
            [self addSubview:rightCoverView];
        }else{
            //
            UIVisualEffectView *visualEffect = [[UIVisualEffectView alloc]initWithEffect:[UIBlurEffect effectWithStyle:UIBlurEffectStyleExtraLight]];
            visualEffect.frame = frame;
            visualEffect.alpha = 1.0;
            [self addSubview:visualEffect];
            leftCoverView = visualEffect;
            //
            frame.origin.x += frame.size.width+self.frame.size.width;
            visualEffect = [[UIVisualEffectView alloc]initWithEffect:[UIBlurEffect effectWithStyle:UIBlurEffectStyleExtraLight]];
            visualEffect.frame = frame;
            visualEffect.alpha = 1.0;
            [self addSubview:visualEffect];
            rightCoverView = visualEffect;
        }
    }
}

- (void)updateShowPageToIndex:(NSInteger)index
{
    [self updateShowPageToIndex:index asynLoad:NO];
}

- (void)updateShowPageToIndex:(NSInteger)index asynLoad:(BOOL)isAsync
{
    if (index <0 || index >= self.pageList.count) {
        NSLog(@"请求超出了，书页编号范畴");
        return;
    }
    CGFloat w = self.bounds.size.width;
    CGFloat h = self.bounds.size.height;
    if (!scrollView) {
        CGRect frame = CGRectMake(0, 0, w, h);
        if (self.pageSize.width && self.pageSize.height) {
            frame.size = self.pageSize;
        }
        self.pageSize = frame.size;
        scrollView = [[UIScrollView alloc] initWithFrame:self.bounds];
        scrollView.center = CGPointMake(w/2, h/2);
        [self addSubview:scrollView];
        scrollView.contentSize = CGSizeMake(w*3, h);
        scrollView.pagingEnabled = YES;
        scrollView.bounces = NO;
        scrollView.delegate = self;
        scrollView.showsHorizontalScrollIndicator = NO;
        scrollView.showsVerticalScrollIndicator = NO;
        //
        CGFloat pod = (w - frame.size.width)/2;
        frame.origin.x = pod;
        pageLeft = [[PageView alloc] initWithFrame:frame];
        pageLeft.max_scale = _max_scale;
        [pageLeft addWaittingView];
        [scrollView addSubview:pageLeft];
        //
        frame.origin.x = w+pod;
        pageCenter = [[PageView alloc] initWithFrame:frame];
        pageCenter.max_scale = _max_scale;
        [pageCenter addWaittingView];
        [scrollView addSubview:pageCenter];
        //
        frame.origin.x = w*2+pod;
        pageRight = [[PageView alloc] initWithFrame:frame];
        pageRight.max_scale = _max_scale;
        [pageRight addWaittingView];
        [scrollView addSubview:pageRight];
        //
        pageCenter.tapCallBackDelegate = pageLeft.tapCallBackDelegate = pageRight.tapCallBackDelegate = self;
        //
        [self update_OutPage_CoverView];//添加iphone等不规则屏幕，投影遮罩效果
    }
    //
//    CGFloat pod = (w - self.pageSize.width)/2;
    //
    BOOL circlePage = __circlePage_;//telen 是否环形翻页控制
    NSInteger index1,index2,index3;
    if (!circlePage && index == 0) {//头
        scrollView.contentOffset = CGPointMake(0, 0);
         _currentPageView = pageLeft;
        //
        index1 = 0, index2 = 1, index3 = 2;
    }else if(!circlePage && index == self.pageList.count-1){//尾
        scrollView.contentOffset = CGPointMake(w*2, 0);
        _currentPageView = pageRight;
        //
        index1 = index-2, index2 = index-1, index3 = index;
    }else{
        scrollView.contentOffset = CGPointMake(w, 0);
        _currentPageView = pageCenter;
        //
        index1 = index-1, index2 = index, index3 = index+1;
        if (circlePage) {
            if (index1 < 0) index1 = self.pageList.count -1;
            if (index3 >= self.pageList.count) index3 = 0;
        }
    }
    NSDictionary* dict = [self.pageList objectAtIndex:index2];
    nullToNil(dict);
    [self pageView:pageCenter formDict:dict];
    pageCenter.pageIndex = index2;
    //
    dict = [self.pageList objectAtIndex:index1];
    nullToNil(dict);
    [self pageView:pageLeft formDict:dict];
    pageLeft.pageIndex = index1;
    //
    dict = [self.pageList objectAtIndex:index3];
    nullToNil(dict);
    [self pageView:pageRight formDict:dict];
    pageRight.pageIndex = index3;
    //
    [pageCenter updatePageShowing_must];
    if (isAsync) {
        [DataProcessing do_Main_quick:^{
            [pageRight updatePageShowing];
            [DataProcessing do_Main_quick:^{
                [pageLeft updatePageShowing];
            }];
        }];
    }else{
        [pageRight updatePageShowing_must];
        [pageLeft updatePageShowing_must];
    }
    //
    pageLeft.alpha = 0.3;
    pageRight.alpha = 0.3;
    pageCenter.alpha = 0.3;
    [UIView animateWithDuration:0.5f animations:^{
        pageLeft.alpha = 1;
        pageRight.alpha = 1;
        pageCenter.alpha = 1;
    }];
}

- (void)prevPage
{
    //放置在涂鸦、便签、剪报模式翻页。主要放置手势翻页
    if (self.currentPageView.memoView.editModel == YES
        || self.currentPageView.scrapView.editModel == YES
        || self.currentPageView.scrawlView.editModel == YES
        ) {
        return;
    }
    //
    [pageLeft.zoomView setZoomScale:1];
    [pageRight.zoomView setZoomScale:1];
    [pageCenter.zoomView setZoomScale:1];
    //
    CGFloat w = self.bounds.size.width;
    CGFloat h = self.bounds.size.height;
    CGFloat pod = (w - self.pageSize.width)/2;
    CGPoint offset = scrollView.contentOffset;
    //居左
    if (fabs(offset.x -pod)<0.1) {
        return;
    }else if (fabs(offset.x - (w*2+pod)) <0.1) { //居右
        CGRect rect = CGRectMake(w+pod, 0, w, h);
        [scrollView scrollRectToVisible:rect animated:YES];
    }else{
        CGRect rect = CGRectMake(pod, 0, w, h);
        [scrollView scrollRectToVisible:rect animated:YES];
    }
}

- (void)nextPage
{
    //放置在涂鸦、便签、剪报模式翻页。主要放置手势翻页
    if (self.currentPageView.memoView.editModel == YES
        || self.currentPageView.scrapView.editModel == YES
        || self.currentPageView.scrawlView.editModel == YES
        ) {
        return;
    }
    //
    [pageLeft.zoomView setZoomScale:1];
    [pageRight.zoomView setZoomScale:1];
    [pageCenter.zoomView setZoomScale:1];
    //
    CGFloat w = self.bounds.size.width;
    CGFloat h = self.bounds.size.height;
    CGFloat pod = (w - self.pageSize.width)/2;
    CGPoint offset = scrollView.contentOffset;
    //居右
    if (fabs(offset.x - (w*2+pod)) <0.1 ) {
        [self pageSrollDo:scrollView cleanKoK:YES];
        [self performSelector:@selector(nextPage) withObject:nil afterDelay:0.1];
        return;
    }else if (fabs(offset.x -pod)<0.1) { //居左
        CGRect rect = CGRectMake(w+pod, 0, w, h);
        if (self.isInBackGround) {
            scrollView.contentOffset = rect.origin;
            [self pageSrolldid:scrollView];
        }else{
            [scrollView scrollRectToVisible:rect animated:YES];
        }
    }else{
        CGRect rect = CGRectMake(w*2+pod, 0, w, h);
        if (self.isInBackGround) {
            scrollView.contentOffset = rect.origin;
            [self pageSrolldid:scrollView];
        }else{
            [scrollView scrollRectToVisible:rect animated:YES];
        }
    }
}

- (void)nextPage_quick
{
    [pageLeft.zoomView setZoomScale:1];
    [pageRight.zoomView setZoomScale:1];
    [pageCenter.zoomView setZoomScale:1];
    //
    CGFloat w = self.bounds.size.width;
    CGFloat h = self.bounds.size.height;
    CGFloat pod = (w - self.pageSize.width)/2;
    CGPoint offset = scrollView.contentOffset;
    //居右
    if (fabs(offset.x - (w*2+pod)) <0.1 ) {
        return;
    }else if (fabs(offset.x - pod)<0.1) { //居左
        CGRect rect = CGRectMake(w+pod, 0, w, h);
        [scrollView scrollRectToVisible:rect animated:NO];
        _currentPageView = pageCenter;
    }else{
        CGRect rect = CGRectMake(w*2+pod, 0, w, h);
        [scrollView scrollRectToVisible:rect animated:NO];
        _currentPageView = pageRight;
    }
    if (_delegate && [_delegate respondsToSelector:@selector(readViewDidScrolledTo:)]) {
        [_delegate readViewDidScrolledTo:_currentPageView];
    }
}

- (void)checkPageScroll
{
    if (_currentPageView != pageCenter) {
        [self pageSrollDo:scrollView cleanKoK:NO];
    }
}

//MARK: pageview数据转换从dict
- (void)pageView:(PageView*)pageview formDict:(NSDictionary*)dict
{
    NSNumber* type_ = [dict objectForKey:@"type"];
    nullToNil(type_);
    NSString* folder_ = [dict objectForKey:@"name"];
    nullToNil(folder_);
    NSNumber* partno_ = [dict objectForKey:@"partno"];
    nullToNil(partno_);
    NSNumber* quizEdition_ = [dict objectForKey:@"quizEdition"];
    nullToNil(quizEdition_);
    pageview.pageType = [type_ integerValue];
    pageview.nameFolder = folder_;
    pageview.zipPartIndex = [partno_ integerValue];
    pageview.bookid = self.bookid;
    pageview.bookOid = self.bookOid;
    pageview.kokColor = self.kokColor;
    pageview.readSource = self.readSource;
    pageview.bookRatioWH = self.bookRatioWH;
    pageview.quizEdition = [quizEdition_ longLongValue];
}

- (void)updatePagesForZipIndex:(NSInteger)zipIndex
{
    if (pageLeft.isWaiting) {//if (pageLeft.zipPartIndex == zipIndex) {
        [pageLeft updatePageShowing_AsyncCtr:^(BOOL hasData) {
            if(hasData){
                NSInteger index = pageLeft.pageIndex;
                NSDictionary* dict = [self.pageList objectAtIndex:index];
                [self pageView:pageLeft formDict:dict];
            }
        } comp:^(BOOL hasData) {
            if (pageLeft == _currentPageView && hasData) {
                pageLeft.alpha = 0.3;
                [UIView animateWithDuration:0.3 animations:^{
                    pageLeft.alpha = 1;
                }];
                if (_delegate && [_delegate respondsToSelector:@selector(readViewDidScrolledTo:)]) {
                    [DataProcessing do_Main_quick:^{
                        [_delegate readViewDidScrolledTo:_currentPageView];
                    }];
                }
            }
        }];
    }
    if (pageRight.isWaiting) {
        [pageRight updatePageShowing_AsyncCtr:^(BOOL hasData) {
            if(hasData){
                NSInteger index = pageRight.pageIndex;
                NSDictionary* dict = [self.pageList objectAtIndex:index];
                [self pageView:pageRight formDict:dict];
            }
        } comp:^(BOOL hasData) {
            if (pageRight == _currentPageView && hasData) {
                pageRight.alpha = 0.3;
                [UIView animateWithDuration:0.3 animations:^{
                    pageRight.alpha = 1;
                }];
                if (_delegate && [_delegate respondsToSelector:@selector(readViewDidScrolledTo:)]) {
                    [DataProcessing do_Main_quick:^{
                        [_delegate readViewDidScrolledTo:_currentPageView];
                    }];
                }
            }
        }];
    }
    if (pageCenter.isWaiting) {
        [pageCenter updatePageShowing_AsyncCtr:^(BOOL hasData) {
            if(hasData){
                NSInteger index = pageCenter.pageIndex;
                NSDictionary* dict = [self.pageList objectAtIndex:index];
                [self pageView:pageCenter formDict:dict];
            }
        } comp:^(BOOL hasData) {
            if (pageCenter == _currentPageView && hasData) {
                pageCenter.alpha = 0.3;
                [UIView animateWithDuration:0.3 animations:^{
                    pageCenter.alpha = 1;
                }];
                if (_delegate && [_delegate respondsToSelector:@selector(readViewDidScrolledTo:)]) {
                    [DataProcessing do_Main_quick:^{
                        [_delegate readViewDidScrolledTo:_currentPageView];
                    }];
                }
            }
        }];
    }
}

- (void)updatePagesEnglishToShow:(BOOL)onOff
{
    pageLeft.en_View.hidden = !onOff;
    pageCenter.en_View.hidden = !onOff;
    pageRight.en_View.hidden = !onOff;
}

- (void)updatePagesChineseToShow:(BOOL)onOff
{
    pageLeft.cn_View.hidden = !onOff;
    pageCenter.cn_View.hidden = !onOff;
    pageRight.cn_View.hidden = !onOff;
}

- (void)updatePagesPinyinToShow:(BOOL)onOff
{
    pageLeft.py_View.hidden = !onOff;
    pageCenter.py_View.hidden = !onOff;
    pageRight.py_View.hidden = !onOff;
}

- (void)updatePagesSreadBtnToShow:(BOOL)onOff
{
    [pageLeft hideSreadBtns:!onOff];
    [pageCenter hideSreadBtns:!onOff];
    [pageRight hideSreadBtns:!onOff];
}

- (void)updatePagesMemosToShow:(BOOL)onOff
{
    pageLeft.memoView.hidden = !onOff;
    pageCenter.memoView.hidden = !onOff;
    pageRight.memoView.hidden = !onOff;
}

- (void)updatePagesCutToShow:(BOOL)onOff
{
    pageLeft.scrapView.hidden = !onOff;
    pageCenter.scrapView.hidden = !onOff;
    pageRight.scrapView.hidden = !onOff;
}

- (void)updatePagesDrawToShow:(BOOL)onOff
{
    pageLeft.scrawlView.hidden = !onOff;
    pageCenter.scrawlView.hidden = !onOff;
    pageRight.scrawlView.hidden = !onOff;
}

- (BOOL)pageSrollDo:(UIScrollView *)sclview cleanKoK:(BOOL)cl
{
    CGFloat w = self.bounds.size.width;
    //    CGFloat pod = (w - self.pageSize.width)/2;
    CGPoint offset = sclview.contentOffset;
    BOOL needNotf = YES;
    BOOL circlePage = __circlePage_;//telen 是否环形翻页控制
    //居左
    if (fabs(offset.x)<1) {
        if (_currentPageView == pageLeft) {
            needNotf = NO;
        }
        _currentPageView = pageLeft;
        if (circlePage || pageLeft.pageIndex != 0) {
            sclview.contentOffset = CGPointMake(w, 0);
            CGRect frame = pageLeft.frame;
            //
            pageLeft.frame = pageCenter.frame;
            pageCenter.frame = pageRight.frame;
            pageRight.frame = frame;
            //
            PageView* temp = pageRight;
            pageRight = pageCenter;
            pageCenter = pageLeft;
            pageLeft = temp;
            //
            NSInteger index = pageCenter.pageIndex-1;
            if (index < 0) index = self.pageList.count -1;
            NSDictionary* dict = [self.pageList objectAtIndex:index];
            nullToNil(dict);
            [self pageView:pageLeft formDict:dict];
            pageLeft.pageIndex = index;
            [pageLeft updatePageShowing];
        }
        //
        if (cl) {
            [pageCenter update_KOK_toPlayMSecond:0 andSentenceIndex:0];
            [pageRight update_KOK_toPlayMSecond:0 andSentenceIndex:0];
        }
    }
    //居中
    if (fabs(offset.x - (w)) < 1 ) {
        if (_currentPageView == pageCenter) {
            needNotf = NO;
        }
        _currentPageView = pageCenter;
        //
        if (cl) {
            [pageLeft update_KOK_toPlayMSecond:0 andSentenceIndex:0];
            [pageRight update_KOK_toPlayMSecond:0 andSentenceIndex:0];
        }
    }
    //居右
    if (fabs(offset.x - (w*2)) < 1 ) {
        if (_currentPageView == pageRight) {
            needNotf = NO;
        }
        _currentPageView = pageRight;
        if (circlePage || pageRight.pageIndex != self.pageList.count-1) {
            sclview.contentOffset = CGPointMake(w, 0);
            CGRect frame = pageRight.frame;
            //
            pageRight.frame = pageCenter.frame;
            pageCenter.frame = pageLeft.frame;
            pageLeft.frame = frame;
            //
            PageView* temp = pageLeft;
            pageLeft = pageCenter;
            pageCenter = pageRight;
            pageRight = temp;
            //
            NSInteger index = pageCenter.pageIndex+1;
            if(index >= self.pageList.count) index = 0;
            NSDictionary* dict = [self.pageList objectAtIndex:index];
            nullToNil(dict);
            [self pageView:pageRight formDict:dict];
            pageRight.pageIndex = index;
            [pageRight updatePageShowing];
        }
        //
        if (cl) {
            [pageCenter update_KOK_toPlayMSecond:0 andSentenceIndex:0];
            [pageLeft update_KOK_toPlayMSecond:0 andSentenceIndex:0];
        }
    }
    return needNotf;
}

- (void)pageSrolldid:(UIScrollView *)sclview
{
    if ([self pageSrollDo:scrollView cleanKoK:YES]) {
        if (_delegate && [_delegate respondsToSelector:@selector(readViewDidScrolledTo:)]) {
            [_delegate readViewDidScrolledTo:_currentPageView];
        }
    }
}

#pragma mark- UIScrollViewDelegate

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    if (_delegate && [_delegate respondsToSelector:@selector(readViewBeganScroll)]) {
        [_delegate readViewBeganScroll];
    }
}

CGFloat distanceBetweenPoints (CGPoint first, CGPoint second) {
    CGFloat deltaX = second.x - first.x;
    CGFloat deltaY = second.y - first.y;
    return sqrt(deltaX*deltaX + deltaY*deltaY );
};

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollVi
{
    PageView* curpageview = self.currentPageView;
    for (UIGestureRecognizer* gest in scrollVi.gestureRecognizers) {
        if([gest isKindOfClass:[UIPanGestureRecognizer class]])
        {
            UIPanGestureRecognizer* gt = (UIPanGestureRecognizer*)gest;
            if (gt.state == UIGestureRecognizerStateEnded
                || gt.state == UIGestureRecognizerStatePossible) {
                CGPoint offset = [gt translationInView:gt.view.superview];
                CGFloat dt = distanceBetweenPoints(offset, CGPointZero);
                if ([self pageSrollDo:scrollView cleanKoK:YES]) {
                    if (_delegate && [_delegate respondsToSelector:@selector(readViewBeganScroll)]) {
                        [_delegate readViewBeganScroll];
                    }
                    if (_delegate && [_delegate respondsToSelector:@selector(readViewBeganScroll_DragEnd)]) {
                        [_delegate readViewBeganScroll_DragEnd];
                    }
                    if (_delegate && [_delegate respondsToSelector:@selector(readViewDidScrolledTo:)]) {
                        [_delegate readViewDidScrolledTo:_currentPageView];
                    }
                }
                if (dt > 10 ) {
                    if (curpageview == self.currentPageView) {
                        if (curpageview == pageRight && offset.x < 0 && fabs(offset.x) > fabs(offset.y)) {
                            //[[WaitingShow shareSingleShow] showString:ReadLocalizedString(@"theLastPage") withIntervalTime:1];
                        }else if(curpageview == pageLeft && offset.x > 0 && fabs(offset.x) > fabs(offset.y)){
                            //[[WaitingShow shareSingleShow] showString:ReadLocalizedString(@"theFristPage") withIntervalTime:1];
                        }
                    }
                    return;
                }else{
                    if (curpageview == self.currentPageView) {
                        if (curpageview == pageRight && offset.x < 0 && fabs(offset.x) > fabs(offset.y)) {
                            //[[WaitingShow shareSingleShow] showString:ReadLocalizedString(@"theLastPage") withIntervalTime:1];
                        }else if(curpageview == pageLeft && offset.x > 10 && fabs(offset.x) > fabs(offset.y)){
                            //[[WaitingShow shareSingleShow] showString:ReadLocalizedString(@"theFristPage") withIntervalTime:1];
                        }
                    }
                    return;
                }
            }
        }
    }
}

- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollVi
{
    [self pageSrolldid:scrollVi];
}

- (void)didPageViewTapRect:(UITapGestureRecognizer_SEL*)tap
{
    if (_delegate && [_delegate respondsToSelector:@selector(readViewDidTapWord:)]) {
        [_delegate readViewDidTapWord:(KoK_RectView*)tap.view];
    }
}

- (void)didPageViewClickedTalk
{
    if (_delegate && [_delegate respondsToSelector:@selector(readViewDidTapWord:)]) {
        [_delegate readView_Accessibility_talkClicked];
    }
}

- (void)sreadBtn_ChangeStatus:(StatusButton_2_View*)sbtn
{
    if (_delegate && [_delegate respondsToSelector:@selector(readViewSReadBtn:status:)]) {
        [_delegate readViewSReadBtn:sbtn status:sbtn.onOff];
    }
}

- (void)didPageViewTapRect_Hot:(UITapGestureRecognizer_SEL*)tap
{
    if (_delegate && [_delegate respondsToSelector:@selector(readViewDidTapHotArea:)]) {
        [_delegate readViewDidTapHotArea:(KoK_RectView*)tap.view];
    }
}

- (void)didPageViewTapRect_Hot_adv:(UITapGestureRecognizer_SEL*)tap
{
    if (_delegate && [_delegate respondsToSelector:@selector(readViewDidTapHotArea_adv:)]) {
        [_delegate readViewDidTapHotArea_adv:(KoK_RectView*)tap.view];
    }
}

- (void)readViewDidLoadSuccess_PageView:(PageView*)pageView
{
    if (_delegate && [_delegate respondsToSelector:@selector(readViewDidLoadSuccess_PageView:)]) {
        [_delegate readViewDidLoadSuccess_PageView:pageView];
    }
}

@end
